/**
* 增强型Http辅助类
* @author zhouli
*
*/
public class EnhancedHttpUtil {
private static HttpClient httpClient;
private static final String TAG = "HttpUtil";
/**
* 获得线程安全的HttpClient对象,能够适应多线程环境
* @return
*/
public static synchronized HttpClient getHttpClient() {
if (null == httpClient) {
HttpParams params = new BasicHttpParams();
// 设置一些基本参数
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params,
"UTF-8");
HttpProtocolParams.setUseExpectContinue(params, true);
HttpProtocolParams
.setUserAgent(
params,
"Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) "
+ "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1");
// 超时设置
/* 从连接池中取连接的超时时间 */
ConnManagerParams.setTimeout(params, 1000);
/* 连接超时 */
HttpConnectionParams.setConnectionTimeout(params, 1000);
/* 请求超时 */
HttpConnectionParams.setSoTimeout(params, 4000);
// 设置我们的HttpClient支持HTTP和HTTPS两种模式
SchemeRegistry schReg = new SchemeRegistry();
schReg.register(new Scheme("http", PlainSocketFactory
.getSocketFactory(), 80));
schReg.register(new Scheme("https", SSLSocketFactory
.getSocketFactory(), 443));
// 使用线程安全的连接管理来创建HttpClient
ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
params, schReg);
httpClient = new DefaultHttpClient(conMgr, params);
}
return httpClient;
}
/**
* 获得Post请求对象
* @param uri 请求地址,也可以带参数
* @param params 如果为null,则不添加由BasicNameValue封装的参数
* @return
*/
public static HttpPost getPost(String uri, List<BasicNameValuePair> params) {
HttpPost post = new HttpPost(uri);
try {
if(params != null) {
post.setEntity(new UrlEncodedFormEntity(params));
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return post;
}
/**
* 用户使用的方法
* 功能:从服务器获得字符串
* @param post
* @return
*/
public static String getString(HttpPost post) {
HttpClient httpClient = getHttpClient();
HttpResponse response;
try {
response = httpClient.execute(post);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
post.abort();
Log.v(TAG, "响应失败,请求终止.");
return null;
}
Log.v(TAG, "响应成功.");
return EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e(TAG, e.getMessage());
return null;
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, e.getMessage());
return null;
}
}
/**
* 用户使用的方法
* 功能:请求服务器,返回字符串
* @param post post 请求对象
* @param requestLimit 请求失败限制次数
* @return
*/
public static String getString(HttpPost post, int requestLimit) {
if (requestLimit < 1) {
return null;
}
HttpResponse response;
int currCount = 0; // 当前请求次数
String result = null;
while (currCount < requestLimit) {
HttpClient httpClient = getHttpClient();
currCount++;
try {
response = httpClient.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
Log.v(TAG, "响应成功.");
return EntityUtils.toString(response.getEntity());
} else {
post.abort();
Log.v(TAG, "响应失败,请求终止.");
result = "响应失败,请求终止.";
}
} catch (ClientProtocolException e) {
Log.e(TAG, e.getMessage());
if (currCount > requestLimit) {
result = "请求失败.";
break;
}
System.out.println("ClientProtocolException");
} catch (IOException e) {
Log.e(TAG, e.getMessage());
if (e instanceof ConnectTimeoutException) {
result = "连接超时.";
} else {
result = "IO异常.";
}
if (currCount > requestLimit) {
break;
}
System.out.println("IOException");
} finally {
System.out.println("finally");
}
}
return result;
}
/**
* 用户使用的方法
* 功能:请求服务器,返回字符串
* @param uri 字符串形式的请求地址
* @param requestLimit 最多允许的请求失败次数
* @return
*/
public static String getString(String uri, int requestLimit) {
if (requestLimit < 1) {
return null;
}
HttpResponse response;
int currCount = 0; // 当前请求次数
String result = null;
HttpPost post = getPost(uri, null);
while (currCount < requestLimit) {
HttpClient httpClient = getHttpClient();
currCount++;
try {
response = httpClient.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
Log.v(TAG, "响应成功.");
return EntityUtils.toString(response.getEntity());
} else {
post.abort();
Log.v(TAG, "响应失败,请求终止.");
result = "响应失败,请求终止.";
}
} catch (ClientProtocolException e) {
Log.e(TAG, e.getMessage());
if (currCount > requestLimit) {
result = "请求失败.";
break;
}
System.out.println("ClientProtocolException");
} catch (IOException e) {
//Log.e(TAG, e.getMessage());
if (e instanceof ConnectTimeoutException) {
result = "连接超时.";
} else {
result = "IO异常.";
}
if (currCount > requestLimit) {
break;
}
//System.out.println("IOException");
} finally {
System.out.println("finally");
}
}
return result;
}
/**
* 释放建立http请求占用的资源
*/
public static void shutdown() {
// 释放建立http请求占用的资源
httpClient.getConnectionManager().shutdown();
httpClient = null;
}
}
使用范例:
[code]
package com.laili;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import com.laili.util.HttpUtil;
public class HttpUtilActivity extends Activity {
private Button btn;
private EditText show;
private String uri = "http://10.2.105.76:8080/json/TestJsonServlet";
private List<BasicNameValuePair> params;
private Handler handler;
private String showStr = "";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
params = new ArrayList<BasicNameValuePair>();
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 0x01:
show.setText(showStr);
break;
}
}
};
show = (EditText) findViewById(R.id.editText1);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
new Thread(){
public void run() {
params.add(new BasicNameValuePair("username", "zhelong"));
params.add(new BasicNameValuePair("password", "123456"));
HttpPost post = HttpUtil.getPost(uri, params);
showStr += HttpUtil.getString(post,3);
//System.out.println(response);
handler.sendEmptyMessage(0x01);
};
}.start();
}
});
}
}
[/code]