您的位置:首页 > 理论基础 > 计算机网络

HttpClient 工具类

2016-01-28 17:02 417 查看
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
* HttpClient访问类
*
* @author jay
* @date 2011.1.1
*/
public class HttpClientUtil {
private static final String APPLICATION_JSON = "application/json";
/**
* HTTP(POST方式)提交
* @param url访问URL
* @param params form表单内容,表单对象类型为:BasicNameValuePair
* @return 返回JSONObject对象
* @throws Exception
*/
public static String post(String url,Map<String,String> params){
String message ="";
try{
CloseableHttpClient httpClient = HttpClients.createDefault();// 创建httpClient链接实例
HttpPost httpPost = null;
CloseableHttpResponse httpResponse = null;
String n_url=url;
httpPost = new HttpPost(n_url);// 创建httppost
List<NameValuePair> list = new ArrayList<NameValuePair>();
Iterator iterator = params.entrySet().iterator();
while(iterator.hasNext()){
Entry<String,String> elem = (Entry<String, String>) iterator.next();
list.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));
}
if(list.size() > 0){
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,"UTF-8");
httpPost.setEntity(entity);
}
httpResponse = httpClient.execute(httpPost);// 执行POST提交请求
HttpEntity r_entity = httpResponse.getEntity();// 获取响应实体
if (r_entity != null) {
message = EntityUtils.toString(r_entity, "UTF-8");
}
if (httpResponse != null) {
httpResponse.close();
}
if (httpClient != null) {
httpClient.close();
}
}catch(Exception ex){
ex.printStackTrace();
}
return message;
}

/**
* HTTP(GET方式)提交
*
* @param url
*            访问URL
* @return JSONObject对象
* @throws Exception
*/
public static String get(String url){
String message="";
try{
CloseableHttpClient httpClient = HttpClients.createDefault();// 创建httpClient链接实例
HttpGet httpGet = null;
CloseableHttpResponse httpResponse = null;
String n_url=url;
httpGet = new HttpGet(n_url);// 创建httpget
httpResponse = httpClient.execute(httpGet);// 执行get提交请求
HttpEntity entity = httpResponse.getEntity();// 获取响应实体
if (entity != null) {
message = EntityUtils.toString(entity, "UTF-8");
}
if (httpResponse != null) {
httpResponse.close();
}
if (httpClient != null) {
httpClient.close();
}
}catch(Exception ex){
ex.printStackTrace();
}
return message;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: