Utils|常用工具类(二)(HttpUtil 发送HTTP请求)
【Utils|常用工具类(二)(HttpUtil 发送HTTP请求)】常用工具类(二):HttpUtil 发送HTTP请求
public class HttpUtil {
private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);
/**
*
* @param url 需要请求的地址
* @param jsonParam 请求地址需要携带的参数
* @return
*/
public static String httpPost(String url, String jsonParam) {
//RequestConfig 用于配置网络环境
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(50000).setConnectTimeout(10000).build();
return httpPostExecute(url,jsonParam,requestConfig);
}public static String httpPostExecute(String url, String jsonParam, RequestConfig requestConfig){
HttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
if (requestConfig != null) httpPost.setConfig(requestConfig);
if (!StringUtils.isEmpty(jsonParam)){
//设置消息体
StringEntity entity = new StringEntity(jsonParam, "utf-8");
entity.setContentEncoding("utf-8");
entity.setContentType("application/json");
httpPost.setHeader("Accept-Encoding","gzip,deflate");
httpPost.setEntity(entity);
}try {
HttpResponse result = httpClient.execute(httpPost);
//encode编码decode解码
url = URLDecoder.decode(url,"utf-8");
if (result.getStatusLine().getStatusCode() == 200) {
String str = "";
Header contentHeader = result.getFirstHeader("Content-Encoding");
if (contentHeader != null && contentHeader.getValue().toLowerCase().indexOf("gzip") > -1) {
str = EntityUtils.toString(new GzipDecompressingEntity(result.getEntity()),"utf-8");
return str;
} else {
str = result.getEntity().toString();
return str;
}
}
} catch (IOException e) {
logger.info(url+"请求失败",e);
}
return null;
}public static String httpGet(String url) {
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(50000).setConnectionRequestTimeout(10000).build();
return httpGetExecute(url,requestConfig);
}public static String httpGetExecute(String url, RequestConfig requestConfig){
HttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
if (requestConfig != null)httpGet.setConfig(requestConfig);
httpGet.setHeader("Accept-Encoding", "gzip,default");
try {
HttpResponse result = httpClient.execute(httpGet);
String str = null;
if (result.getStatusLine().getStatusCode() == 200) {
Header contentHeader = result.getFirstHeader("Content-Encoding");
if (contentHeader != null && contentHeader.getValue().toLowerCase().indexOf("gzip") > -1) {
str = EntityUtils.toString(new GzipDecompressingEntity(result.getEntity()));
return str;
} else {
str = EntityUtils.toString(result.getEntity(),"utf-8");
return str;
}
}
} catch (IOException e) {
logger.info(url+"请求失败",e);
}
return null;
}
}
推荐阅读
- JAVA(抽象类与接口的区别&重载与重写&内存泄漏)
- 为什么你的路演总会超时()
- 标签、语法规范、内联框架、超链接、CSS的编写位置、CSS语法、开发工具、块和内联、常用选择器、后代元素选择器、伪类、伪元素。
- thinkphp|thinkphp 3.2 如何调用第三方类库
- 使用composer自动加载类文件
- 一个健康的APP和健全的人格大体类似
- 种树郭橐驼传(文言句式+古今异义+词类活用+通假字)
- 归乡-序章(世界伊始,人类无所依靠,我的故事就从这里开始...)
- jQuery插件
- 第十六天(请介绍一件让你非常自豪的事情,(不能是职业类的),什么原因感到自豪。)