Android学习笔记:利用httpclient和AsyncTask 发起网络http post操作

时间:2022-12-21 20:33:22

1、在android4中,发起网络http操作,不能在Activity的事件(即主线程)中进行,必须在单独的线程中操作。

另外进行网络操作,需要在manifest文件中增加如下的权限:

<uses-permission android:name="android.permission.INTERNET" />

2、下面给出代码事例

	public void loadData() {
new AsyncTask<String, Void, String>() {
@Override
protected String doInBackground(String... paramsInput) {
String url = "http://10.0.0.5:8080/examples/action";
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("type", paramsInput[0]));
params.add(new BasicNameValuePair("id", paramsInput[1]));
/* 建立HTTPPost对象 */
HttpPost httpRequest = new HttpPost(url); String strResult = "doPostError";
try {
HttpClient httpClient = getHttpClient();
/* 添加请求参数到请求对象 */
httpRequest.setEntity(new UrlEncodedFormEntity(params,
HTTP.UTF_8));
/* 发送请求并等待响应 */
HttpResponse httpResponse = httpClient.execute(httpRequest);
/* 若状态码为200 ok */
if (httpResponse.getStatusLine().getStatusCode() == 200) {
/* 读返回数据 */
strResult = EntityUtils.toString(httpResponse
.getEntity()); } else {
strResult = "Error Response: "
+ httpResponse.getStatusLine().toString();
}
} catch (ClientProtocolException e) {
strResult = "Error Response: " + e.getMessage().toString();
e.printStackTrace();
} catch (IOException e) {
strResult = "Error Response: " + e.getMessage().toString();
e.printStackTrace();
} catch (Exception e) {
strResult = "Error Response: " + e.getMessage().toString();
e.printStackTrace();
}
return strResult;
} @Override
protected void onPostExecute(String result) {
TextView view = (TextView) findViewById(R.id.resultText);
view.setText(result);
super.onPostExecute(result);
} }.execute("query","1");
} private HttpClient getHttpClient() { // 创建 HttpParams 以用来设置 HTTP 参数(这一部分不是必需的) HttpParams httpParams = new BasicHttpParams(); // 设置连接超时和 Socket 超时,以及 Socket 缓存大小 HttpConnectionParams.setConnectionTimeout(httpParams, 20 * 1000); HttpConnectionParams.setSoTimeout(httpParams, 20 * 1000); HttpConnectionParams.setSocketBufferSize(httpParams, 8192); // 设置重定向,缺省为 true HttpClientParams.setRedirecting(httpParams, true); // 设置 user agent String userAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2) Gecko/20100115 Firefox/3.6";
HttpProtocolParams.setUserAgent(httpParams, userAgent); // 创建一个 HttpClient 实例 // 注意 HttpClient httpClient = new HttpClient(); 是Commons HttpClient // 中的用法,在 Android 1.5 中我们需要使用 Apache 的缺省实现 DefaultHttpClient HttpClient httpClient = new DefaultHttpClient(httpParams); return httpClient;
}

 上述代码的loadData方法中,创建一个AsyncTask对象,在对象的doInBackground方法中发起网络操作,获取到操作结果。然后在onPostExecute方法中,利用前面获取到的结果更新界面。

这里的网络操作主要是利用了HttpClient等相关api,位于org.apache.http.client.HttpClient下。