HttpUtil工具類
原文:https://zhelong111.iteye.com/blog/1407117
/**
* 增強型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;
}
}
使用範例: 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 = "https://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();
}
});
}
}
最後更新:2017-04-02 18:44:44