通過http rest請求返回資料
複製程式碼 程式碼如下:
import ;
import actory;
import ValuePair;
import ntProtocolException;
import Client;
import onseHandler;
import ncodedFormEntity;
import Get;
import Post;
import cResponseHandler;
import ultHttpClient;
import adSafeClientConnManager;
import ception;
import ageFormat;
import ;
import Unit;
/**
* 分裝一個http請求的.工具類
*
* @author 顧煒【guwei】 on 14-4-22.下午3:17
*/
public class HttpClientUtils {
private static final Log log = og(s);
/**
* 初始化HttpClient
*/
private static HttpClient httpClient = null;
/**
* 生產HttpClient例項
* 公開,靜態的工廠方法,需要使用時才去建立該單體
*
* @return
*/
public static HttpClient getHttpClient() {
if (httpClient == null) {
httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager());
}
return httpClient;
}
/**
* POST方式呼叫
*
* @param url
* @param params 引數為NameValuePair鍵值對物件
* @return 響應字串
* @throws pportedEncodingException
*/
public static String executeByPOST(String url, Listparams) {
HttpClient httpclient = getHttpClient();
HttpPost post = new HttpPost(url);
ResponseHandlerresponseHandler = new BasicResponseHandler();
String responseJson = null;
try {
if (params != null) {
ntity(new UrlEncodedFormEntity(params));
}
responseJson = ute(post, responseHandler);
("HttpClient POST請求結果:" + responseJson);
} catch (ClientProtocolException e) {
tStackTrace();
("HttpClient POST請求異常:" + essage());
} catch (IOException e) {
tStackTrace();
} finally {
onnectionManager()eExpiredConnections();
onnectionManager()eIdleConnections(30, NDS);
}
return responseJson;
}
/**
* Get方式請求
*
* @param url 帶引數佔位符的URL,例:http://****/User/user/{0}&email={1}
* @param params 引數值陣列,需要與url中佔位符順序對應
* @return 響應字串
* @throws pportedEncodingException
*/
public static String executeByGET(String url, Object[] params) {
HttpClient httpclient = getHttpClient();
String messages = at(url, params);
HttpGet get = new HttpGet(messages);
ResponseHandlerresponseHandler = new BasicResponseHandler();
String responseJson = null;
try {
responseJson = ute(get, responseHandler);
("HttpClient GET請求結果:" + responseJson);
} catch (ClientProtocolException e) {
tStackTrace();
("HttpClient GET請求異常:" + essage());
} catch (IOException e) {
tStackTrace();
("HttpClient GET請求異常:" + essage());
} finally {
onnectionManager()eExpiredConnections();
onnectionManager()eIdleConnections(30, NDS);
}
return responseJson;
}
/**
* @param url
* @return
*/
public static String executeByGET(String url) {
HttpClient httpclient = getHttpClient();
HttpGet get = new HttpGet(url);
ResponseHandlerresponseHandler = new BasicResponseHandler();
String responseJson = null;
try {
responseJson = ute(get, responseHandler);
("HttpClient GET請求結果:" + responseJson);
} catch (ClientProtocolException e) {
tStackTrace();
("HttpClient GET請求異常:" + essage());
} catch (IOException e) {
tStackTrace();
("HttpClient GET請求異常:" + essage());
} finally {
onnectionManager()eExpiredConnections();
onnectionManager()eIdleConnections(30, NDS);
}
return responseJson;
}
}