maven依赖
org.apache.httpcomponents
httpclient
4.5.2
package com.djhu.wechat.followup.utils;
import net.sf.json.JSONObject;
import org.apache.commons.collections.MapUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.*;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
-
@Description
-
@Author jianda.deng
-
@Time 2017/5/5 10:38
*/
public class HttpRequestUtils {
private static Logger logger = LoggerFactory.getLogger(HttpRequestUtils.class); //日志记录/**
- httpPost
- @param url 路径
- @param map 参数
- @return
*/
public static JSONObject httpPost(String url, Map<String, Object> map){
return httpPost(url, map, false);
}
/**
- post请求
- @param url url地址
- @param map 参数
- @param noNeedResponse 不需要返回结果
- @return
*/
public static JSONObject httpPost(String url, Map<String, Object> map, boolean noNeedResponse){
//post请求返回结果
DefaultHttpClient httpClient = new DefaultHttpClient();
JSONObject jsonResult = null;
HttpPost method = new HttpPost(url);
try {
if (MapUtils.isNotEmpty(map)) {
//设置参数
List list = new ArrayList();
Iterator iterator = map.entrySet().iterator();
while(iterator.hasNext()){
Entry<String,Object> elem = (Entry<String, Object>) iterator.next();
list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()+""));
}
if(list.size() > 0){
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,“utf-8”);
method.setEntity(entity);
}
}
HttpResponse result = httpClient.execute(method);
url = URLDecoder.decode(url, “UTF-8”);
/请求发送成功,并得到响应/
if (result.getStatusLine().getStatusCode() == 200) {
if (noNeedResponse) {
return null;
}
String str = “”;
try {
/读取服务器返回过来的json字符串数据/
str = EntityUtils.toString(result.getEntity(), “UTF-8”);
/把json字符串转换成json对象/
jsonResult = JSONObject.fromObject(str);
} catch (Exception e) {
logger.error(“post请求提交失败:” + url, e);
}
}
} catch (IOException e) {
logger.error(“post请求提交失败:” + url, e);
}
return jsonResult;
}
/**
-
post请求
-
@param url url地址
-
@param jsonParam 参数
-
@return
*/
public static String httpPostForString(String url, JSONObject jsonParam){
//post请求返回结果
//DefaultHttpClient httpClient = new DefaultHttpClient();
HttpClientBuilder builder = HttpClients.custom()
.disableAutomaticRetries() //关闭自动处理重定向
.setRedirectStrategy(new LaxRedirectStrategy());//利用LaxRedirectStrategy处理POST重定向问题
CloseableHttpClient httpClient = builder.build();
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(500000).setConnectionRequestTimeout(100000)
.setSocketTimeout(500000).build();
HttpPost method = new HttpPost(url.trim());
method.setConfig(requestConfig);
try {
if (null != jsonParam) {
//解决中文乱码问题
StringEntity entity = new StringEntity(jsonParam.toString(), “utf-8”);
entity.setContentEncoding(“UTF-8”);
entity.setContentType(“application/json”);
method.setEntity(entity);
}
url = URLDecoder.decode(url, “UTF-8”);
//httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000);
HttpResponse result = httpClient.execute(method);
/请求发送成功,并得到响应/
if (result.getStatusLine().getStatusCode() == 200) {
try {
/读取服务器返回过来的json字符串数据/
return EntityUtils.toString(result.getEntity(), “UTF-8”);} catch (Exception e) { logger.error("post请求提交失败:" + url, e); } }
} catch (IOException e) {
logger.error(“post请求提交失败:” + url, e);
}
return null;
}
/**
-
发送get请求
-
@param url 路径
-
@return
*/
public static JSONObject httpGet(String url){
//get请求返回结果
JSONObject jsonResult = null;
try {
DefaultHttpClient client = new DefaultHttpClient();
//发送get请求
//url= URLEncoder.encode(url,“utf-8”);
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);/**请求发送成功,并得到响应**/ if (response.getStatusLine().getStatusCode() == 200) { /**读取服务器返回过来的json字符串数据**/ String strResult = EntityUtils.toString(response.getEntity()); /**把json字符串转换成json对象**/ jsonResult = JSONObject.fromObject(strResult); url = URLDecoder.decode(url, "UTF-8"); } else { logger.error("get请求提交失败:" + url); }
} catch (IOException e) {
logger.error(“get请求提交失败:” + url, e);
}
return jsonResult;
}
public static JSONObject getHttpPostForMap(String url,Map<String, Object>param){
if(url==null||"".equals(url))return new JSONObject();
JSONObject result= httpPost(url,param);
return result;
}public static JSONObject getHttpPostForString(String url,JSONObject jsonParama){
if(url==null||"".equals(url)) {
logger.info(“请求地址为空,param:{}”, jsonParama);
return new JSONObject();
}
String result= httpPostForString(url,jsonParama);
JSONObject jsonResult = JSONObject.fromObject(result);
return jsonResult;
}
}