主要实现:客户端访问服务端,服务端响应并且返回数据给客户端,这里主要目的就是会使用封装类
1、这里还是先建一个XML,定义button(点击),TextView(显示数据)具体如下代码:
<span style="font-size:18px;"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="buttonbackss"
android:text="点击封装类获取返回数据"/>
<TextView
android:id="@+id/txtViews"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
</span>
<span style="font-size:18px;">2、新建Activti继承Activty</span>
<span style="font-size:18px;">这里的网络封装类写成了内部类,当然也可以单独拿出来作为类,代码如下:</span>
<pre name="code" class="html"><span style="font-size:18px;">package com.example.com.scxh.httpservicehuoqu;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpInetConnection;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import com.example.com.scxh.httpservicehuoqu.HttpConnectUtil.HttpConnectInterface;
import com.example.com.scxh.httpservicehuoqu.HttpConnectUtil.HttpMethod;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class HttpFengZhuang extends Activity {
private TextView mTextView, mTextView2;
private Button button, button2;
// 某一服服務端的地址(本地地址/服务端端口/服务端文件夹名(web)/web文件夹里自动生成的web.xml里的自定义名)
private String httpUrl = "http://192.168.1.148:8080/ServletProject/firstservlet";
// private String httpUrls = "http://192.168.1.196:8080/jk/loginservlet";
private String httpUrlss = "http://192.168.1.148:8080/ServletProject/firstservlet";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.httpfengzhuang);
mTextView2 = (TextView) findViewById(R.id.txtViews);
}
// -----------------------------封装按钮监听-------------------------------------------------------
public void buttonbackss(View v) {
// 实例化网络封装类
HttpConnectUtil mhConnectUtil = new HttpConnectUtil();
// 回调接口实现
HttpConnectInterface mHttpConnectInterface = new HttpConnectInterface() {
@Override
public void execute(String result) {
Log.v("tag", "理服务器返回数据 HttpConnectInterface result" + result);
mTextView2.setText(result); // .处理服务器返回数据
}
};
// 注册回调接口
mhConnectUtil.setmHttpConnectInterface(mHttpConnectInterface);
// 参数
HashMap<String, String> map = new HashMap<String, String>();
map.put("username", "老大");
map.put("password", "1234555");
map.put("sex", "男");
Log.v("tag", "1111111111111111");
// 发起网络请求
mhConnectUtil.asyncConnect(httpUrlss, HttpMethod.POST, map);
Log.v("tag", "22222222222");
// HttpConnections hh=new HttpConnections(httpUrls, HttpMethod.GET,map);
// hh.myasyntask();
}
}
//已封装好的类
class HttpConnectUtil {
public static enum HttpMethod {
GET, POST
};
// ---------------回调接口实现 参见接口实现步骤--------------------
private HttpConnectInterface mHttpConnectInterface;
public interface HttpConnectInterface {
public void execute(String result);
}
public void setmHttpConnectInterface(
HttpConnectInterface mHttpConnectInterface) {
this.mHttpConnectInterface = mHttpConnectInterface;
}
// ---------------------------------------------
public void asyncConnect(final String httpUrl, final HttpMethod httpMethod) {
asyncConnect(httpUrl, httpMethod, null);
}
public void asyncConnectJson(final String httpUrl,
final HttpMethod httpMethod) {
asyncConnectJson(httpUrl, httpMethod, null);
}
public void asyncConnect(final String httpUrl, final HttpMethod httpMethod,
final HashMap<String, String> parameters) {
new AsyncTask<String, Void, String>() {
@Override
protected String doInBackground(String... params) {
String url = params[0];
Log.v("tag", "asyncConnect" + url);
return getDataByHttpClient(url, httpMethod, parameters);
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
mHttpConnectInterface.execute(result);
}
}.execute(httpUrl);
}
public void asyncConnectJson(final String httpUrl,
final HttpMethod httpMethod,
final HashMap<String, String> parameters) {
new AsyncTask<String, Void, String>() {
@Override
protected String doInBackground(String... params) {
String url = params[0];
return getJsonDataByHttpClient(url, httpMethod, parameters);
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.v("tag", "onPostExecute " + result);
mHttpConnectInterface.execute(result);
}
}.execute(httpUrl);
}
/**
*
* @param httpUrl
* :http://192.168.1.11/xinhuaApp/login
* @param httpMethod
* @param parameters
* httpUrl = httpUrl + "?name=xinhua&password=123456";
* @return
*/
private HttpUriRequest getHttpRequest(String httpUrl,
final HttpMethod httpMethod,
final HashMap<String, String> parameters) {
if (httpMethod.equals(HttpMethod.GET)) {
if (parameters != null) {
StringBuilder sb = new StringBuilder("?");
for (String name : parameters.keySet()) { // 循环遍历HashMap取出参数组装成字符串
String key = name;
String value = parameters.get(key);
sb.append(key);
sb.append("=");
try {
sb.append(URLEncoder.encode(value, HTTP.UTF_8));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
sb.append("&");
}
sb.substring(0, sb.length() - 1);
httpUrl = httpUrl + sb.toString();
}
HttpGet httpGet = new HttpGet(httpUrl);
return httpGet;
} else {
HttpPost httpPost = new HttpPost(httpUrl);
if (parameters != null) {
List<BasicNameValuePair> listParams = new ArrayList<BasicNameValuePair>();
for (String name : parameters.keySet()) {
String key = name;
String value = null;
value = parameters.get(key);
listParams.add(new BasicNameValuePair(key, value));
}
// 用UrlEncodedFormEntity来封装List对象
UrlEncodedFormEntity urlEntity;
try {
urlEntity = new UrlEncodedFormEntity(listParams, HTTP.UTF_8);
// 设置使用的Entity
httpPost.setEntity(urlEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return httpPost;
}
}
/**
* 从网络获取数据通过HttpClient方式实现 get方式
*
* @param url
* @return
*/
private String getDataByHttpClient(String httpUrl,
final HttpMethod httpMethod,
final HashMap<String, String> parameters) {
BufferedReader br = null;
InputStream is = null;
StringBuilder sb = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpUriRequest httpUriRequest = getHttpRequest(httpUrl, httpMethod,
parameters);
HttpResponse httpResponse;
try {
httpResponse = httpClient.execute(httpUriRequest);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
int statusCode = httpResponse.getStatusLine().getStatusCode();
Log.v("tag", "statusCode" + statusCode);
if (statusCode == HttpURLConnection.HTTP_OK) {
// 创建包装流
br = new BufferedReader(new InputStreamReader(is));
// 定义String类型用于储存单行数据
String line = null;
// 创建StringBuffer对象用于存储所有数据
while ((line = br.readLine()) != null) {
sb.append(line);
}
Log.v("tag", "sb.tostring : " + sb.toString());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
private String getJsonDataByHttpClient(String httpUrl,
final HttpMethod httpMethod,
final HashMap<String, String> parameters) {
BufferedReader br = null;
InputStream is = null;
StringBuilder sb = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpUriRequest httpUriRequest = getHttpRequest(httpUrl, httpMethod,
parameters);
HttpResponse httpResponse;
try {
httpResponse = httpClient.execute(httpUriRequest);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
return readStream(is);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
public String readStream(InputStream is) {
try {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
int i = is.read();
while (i != -1) {
bo.write(i);
i = is.read();
}
return bo.toString();
} catch (IOException e) {
return "";
}
}
}
class HttpConnections {
private String url = null;
private HashMap hashmap = null;
private HttpMethod httpmethod = null;
public HttpConnections(String murl, HttpMethod mhttpmethod, HashMap mhashmap) {
url = murl;
httpmethod = mhttpmethod;
hashmap = mhashmap;
}
public void myasyntask() {
new AsyncTask<String, Void, String>() {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpresponse = null;
@Override
protected String doInBackground(String... params) {
if (httpmethod.equals(HttpMethod.GET)) {
InputStream is = null;
BufferedReader br = null;
StringBuffer sb = null;
try {
httpresponse = httpclient.execute(setData(url,
httpmethod, hashmap));
is = httpresponse.getEntity().getContent();
br = new BufferedReader(new InputStreamReader(is));
String line = null;
sb = new StringBuffer();
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return sb.toString();
}
if (httpmethod.equals(HttpMethod.POST)) {
try {
httpresponse = httpclient.execute(setData(url,
httpmethod, hashmap));
Log.e("httpresponse", httpresponse + "");
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (httpmethod.equals(HttpMethod.GET)) {
// mTextView2.setText(s);
Log.e("s", s);
}
}
}.execute();
}
public HttpUriRequest setData(String url, HttpMethod httpMethod,
HashMap<String, String> hashMap) {
if (httpMethod.equals(HttpMethod.GET)) {
StringBuffer sb = new StringBuffer();
String path = null;
sb.append("?");
if (hashMap != null) {
for (String key : hashMap.keySet()) {
sb.append(key);
sb.append("=");
sb.append(hashMap.get(key));
sb.append("&");
}
}
path = url + sb.toString();
path = path.substring(0, path.length() - 1);
HttpGet httpGet = new HttpGet(path);
return httpGet;
}
if (httpMethod.equals(HttpMethod.POST)) {
StringBuffer sb = new StringBuffer();
String path = url;
ArrayList list = new ArrayList();
UrlEncodedFormEntity urlEncodedFormEntity = null;
if (hashMap != null) {
for (String key : hashMap.keySet()) {
BasicNameValuePair basicNameValuePair = new BasicNameValuePair(
key, hashMap.get(key));
Log.e("map", key + " " + hashMap.get(key));
list.add(basicNameValuePair);
}
try {
urlEncodedFormEntity = new UrlEncodedFormEntity(list,
"utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Log.e("path", path);
HttpPost httpPost = new HttpPost(path);
httpPost.setEntity(urlEncodedFormEntity);
return httpPost;
}
}
return null;
}
}
</span>
<span style="font-size:18px;">
</span>