关于java实现http请求工具类示例
通过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;
}
}