HttpClient工具类

package cn.sh.steven.httpclient;import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
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.client.utils.URLEncodedUtils;
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.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;public class HttpToolUtils {private static final Logger log = LoggerFactory.getLogger(HttpToolUtils.class);private static RequestConfig requestConfig;static {requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectionRequestTimeout(5000).setConnectTimeout(5000).build();}/*** 发送HTTP_GET请求** @param reqURL        请求地址(含参数)* @param decodeCharset 解码字符集,解析响应数据时用之,其为null时默认采用UTF-8解码* @return 远程主机响应正文*/public static String sendGetRequest(String reqURL, String decodeCharset) {long responseLength = 0;       //响应长度CloseableHttpClient httpClient = HttpClients.createDefault();String responseContent = null; //响应内容HttpGet httpGet = new HttpGet(reqURL);           //创建org.apache.http.client.methods.HttpGettry {HttpResponse response = httpClient.execute(httpGet); //执行GET请求HttpEntity entity = response.getEntity();            //获取响应实体if (null != entity) {responseLength = entity.getContentLength();responseContent = EntityUtils.toString(entity, decodeCharset == null ? "UTF-8" : decodeCharset);EntityUtils.consume(entity); //Consume response content}System.out.println("请求地址: " + httpGet.getURI());System.out.println("响应状态: " + response.getStatusLine());System.out.println("响应长度: " + responseLength);System.out.println("响应内容: " + responseContent);} catch (ClientProtocolException e) {log.debug("该异常通常是协议错误导致,比如构造HttpGet对象时传入的协议不对(将'http'写成'htp')或者服务器端返回的内容不符合HTTP协议要求等,堆栈信息如下", e);} catch (ParseException e) {log.debug(e.getMessage(), e);} catch (IOException e) {log.debug("该异常通常是网络原因引起的,堆栈信息如下", e);} finally {httpGet.releaseConnection(); //关闭连接,释放资源}return responseContent;}/*** @param url       url地址* @param jsonParam 参数* @return JSONObject*/public static JSONObject httpPost(String url, JSONObject jsonParam) {CloseableHttpClient httpClient = HttpClients.createDefault();// post请求返回结果JSONObject jsonResult = null;HttpPost httpPost = new HttpPost(url);// 设置请求和传输超时时间httpPost.setConfig(requestConfig);try {if (null != jsonParam) {httpPost.setHeader("Content-type", "application/json");// 解决中文乱码问题StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");entity.setContentEncoding("UTF-8");httpPost.setEntity(entity);}CloseableHttpResponse response = httpClient.execute(httpPost);if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {String s = EntityUtils.toString(response.getEntity(), "utf-8");jsonResult = JSONObject.parseObject(s);// 请求发送成功,并得到响应log.info("post请求成功,响应数据:{}", jsonResult);}} catch (IOException e) {log.error("post请求提交失败,异常信息:{}", e.getStackTrace());} finally {httpPost.releaseConnection();}return jsonResult;}/*** @param url       url地址* @param jsonParam 参数* @return String*/public static String sendPost(String url, JSONObject jsonParam) {CloseableHttpClient httpClient = HttpClients.createDefault();// post请求返回结果String s = null;HttpPost httpPost = new HttpPost(url);// 设置请求和传输超时时间httpPost.setConfig(requestConfig);try {if (null != jsonParam) {httpPost.setHeader("Content-type", "application/json");// 解决中文乱码问题StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");entity.setContentEncoding("UTF-8");httpPost.setEntity(entity);}CloseableHttpResponse response = httpClient.execute(httpPost);log.info("调用接口返回response{}", response);if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {s = EntityUtils.toString(response.getEntity(), "utf-8");// 请求发送成功,并得到响应log.info("post请求成功,响应数据:{}", s);}} catch (IOException e) {log.error("post请求提交失败,异常信息:{}", e);} finally {httpPost.releaseConnection();}return s;}/*** 发送HTTP_POST请求** @param isEncoder 用于指明请求数据是否需要UTF-8编码,true为需要* @see //该方法为<code>sendPostRequest(String,String,boolean,String,String)</code>的简化方法* @see //该方法在对请求数据的编码和响应数据的解码时,所采用的字符集均为UTF-8* @see //当<code>isEncoder=true</code>时,其会自动对<code>sendData</code>中的[中文][|][ ]等特殊字符进行<code>URLEncoder.encode(string,"UTF-8")</code>*/public static String sendPostRequest(String reqURL, String sendData, boolean isEncoder) {return sendPostRequest(reqURL, sendData, isEncoder, null, null);}/*** 发送HTTP_POST请求** @param reqURL        请求地址* @param sendData      请求参数,若有多个参数则应拼接成param11=value11&22=value22&33=value33的形式后,传入该参数中* @param isEncoder     请求数据是否需要encodeCharset编码,true为需要* @param encodeCharset 编码字符集,编码请求数据时用之,其为null时默认采用UTF-8解码* @param decodeCharset 解码字符集,解析响应数据时用之,其为null时默认采用UTF-8解码* @return 远程主机响应正文* @see //该方法会自动关闭连接,释放资源* @see //当<code>isEncoder=true</code>时,其会自动对<code>sendData</code>中的[中文][|][ ]等特殊字符进行<code>URLEncoder.encode(string,encodeCharset)</code>*/public static String sendPostRequest(String reqURL, String sendData, boolean isEncoder, String encodeCharset, String decodeCharset) {String responseContent = null;CloseableHttpClient httpClient = HttpClients.createDefault();HttpPost httpPost = new HttpPost(reqURL);httpPost.setHeader("X-APP-ID", "eb77fe57515a9d8efe137278181e08a4");httpPost.setHeader("X-APP-KEY", "2f4bb04c0f4aa02c85e91a7c64a41f52");httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8");try {if (isEncoder) {List<NameValuePair> formParams = new ArrayList<NameValuePair>();for (String str : sendData.split("&")) {formParams.add(new BasicNameValuePair(str.substring(0, str.indexOf("=")), str.substring(str.indexOf("=") + 1)));}httpPost.setEntity(new StringEntity(URLEncodedUtils.format(formParams, encodeCharset == null ? "UTF-8" : encodeCharset)));} else {String s;StringEntity stringEntity = new StringEntity(sendData);stringEntity.setContentType("text/json");httpPost.setEntity(stringEntity);}HttpResponse response = httpClient.execute(httpPost);HttpEntity entity = response.getEntity();if (null != entity) {responseContent = EntityUtils.toString(entity, decodeCharset == null ? "UTF-8" : decodeCharset);EntityUtils.consume(entity);}} catch (Exception e) {log.info("与[" + reqURL + "]通信过程中发生异常,堆栈信息如下", e);} finally {httpPost.releaseConnection();}return responseContent;}/*** 发送HTTP_POST请求** @param reqURL        请求地址* @param sendData      请求参数,若有多个参数则应拼接成param11=value11&22=value22&33=value33的形式后,传入该参数中* @return 远程主机响应正文* @see //该方法会自动关闭连接,释放资源* @see //当<code>isEncoder=true</code>时,其会自动对<code>sendData</code>中的[中文][|][ ]等特殊字符进行<code>URLEncoder.encode(string,encodeCharset)</code>*/public static String sendPostRequest(String reqURL, String sendData) {String responseContent = null;CloseableHttpClient httpClient = HttpClients.createDefault();HttpPost httpPost = new HttpPost(reqURL);httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8");try {StringEntity stringEntity = new StringEntity(sendData,"UTF-8");stringEntity.setContentType("application/json");httpPost.setEntity(stringEntity);RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(90000).setConnectionRequestTimeout(90000).setSocketTimeout(90000).build();httpPost.setConfig(requestConfig);HttpResponse response = httpClient.execute(httpPost);HttpEntity entity = response.getEntity();if (null != entity) {responseContent = EntityUtils.toString(entity, "UTF-8");EntityUtils.consume(entity);}} catch (Exception e) {log.info("与[" + reqURL + "]通信过程中发生异常,堆栈信息如下", e);} finally {httpPost.releaseConnection();}return responseContent;}/*** 发送HTTP_POST请求** @param reqURL 请求地址* @param params 请求参数* @return 远程主机响应正文* @see //该方法会自动关闭连接,释放资源* @see //该方法会自动对<code>params</code>中的[中文][|][ ]等特殊字符进行<code>URLEncoder.encode(string,encodeCharset)</code>*/public static String sendPostRequest(String reqURL, Map<String, String> params) {String responseContent = null;CloseableHttpClient httpClient = HttpClients.createDefault();HttpPost httpPost = new HttpPost(reqURL);httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json");List<NameValuePair> formParams = new ArrayList<NameValuePair>(); //创建参数队列for (Map.Entry<String, String> entry : params.entrySet()) {formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));}try {httpPost.setEntity(new UrlEncodedFormEntity(formParams, "utf-8"));log.info("http远程调用开始……");HttpResponse response = httpClient.execute(httpPost);log.info("http远程调用返回:{}", JSON.toJSONString(response));HttpEntity entity = response.getEntity();log.info("远程调用返回entity:{}", JSON.toJSONString(entity));if (null != entity) {responseContent = EntityUtils.toString(entity, "utf-8");log.info("远程调用返回responseContent:{}", JSON.toJSONString(responseContent));EntityUtils.consume(entity);}} catch (Exception e) {log.info("与[" + reqURL + "]通信过程中发生异常,堆栈信息如下", e);} finally {httpPost.releaseConnection();}return responseContent;}}

HttpClient工具类相关推荐

  1. Java开发小技巧(五):HttpClient工具类

    前言 大多数Java应用程序都会通过HTTP协议来调用接口访问各种网络资源,JDK也提供了相应的HTTP工具包,但是使用起来不够方便灵活,所以我们可以利用Apache的HttpClient来封装一个具 ...

  2. apache httpclient 工具类_HttpClient

    HttpClient 简介 HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的.最新的.功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 ...

  3. apache httpclient 工具类_HttpClient 和Mycat 主从节点和读写分离

    第175次(HttpClient) 学习主题:HttpClient 学习目标: 1 掌握HttpClient自定义工具以及HttpClient具体的使用 对应视频: http://www.itbaiz ...

  4. apache httpclient 工具类_使用HttpClient进行服务的远程调用

    目标:使用apache公司的产品http httpcomponents 完成服务调用. HTTPClient调用服务 4:导入httpclient的依赖配置 org.apache.httpcompon ...

  5. 使用单例模式实现自己的HttpClient工具类

    本文转载自:http://www.cnblogs.com/codingmyworld/archive/2011/08/17/2141706.html 使用单例模式实现自己的HttpClient工具类 ...

  6. 14、阿里云短信Demo演示、Http的Get请求和Post请求演示、httpClient工具类演示、发送短信模块搭建、搭建用户中心模块、完成user注册基本功能、验证码存入redis、短信验证码注册

    阿里云短信Demo演示 一.前端部分 无前端. 二.后端部分 1.创建发送短信测试模块SmsSendDemo,不用使用骨架. 2.在pom文件中引入依赖坐标 <dependency>< ...

  7. 工具类-httpClient工具类

    httpClient工具类 1.httpClient工具类(http/https.重发.超时.连接数的设置) package com.xxxxxxx.xxxx.xxxx.payutil;import ...

  8. HttpClient工具类封装

    HttpClient是Apache Jakarta Common下的子项目,用来提供高效的.最新的.功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议.HttpCli ...

  9. HttpClient工具类及应用

    Content-Type类型: 常见的媒体格式类型如下: text/html : HTML格式 text/plain :纯文本格式 text/xml : XML格式 image/gif :gif图片格 ...

最新文章

  1. 本硕非科班,单模型获得亚军!
  2. 大厂面试录取通过率不到3%,我真是太太太难了......
  3. 影响线型缩聚物分子量的因素_运城专业超高分子量聚乙烯油井内衬管生产基地...
  4. 超级全的 SCI 写作句式模板
  5. const char *p,char const *p, char * const p之间的区别
  6. Mysql函数示例(如何定义输入变量与返回值)
  7. Git 简单命令行指令
  8. 国产OS推广应从娃娃和体制内双管齐下
  9. 在linux环境下安装wiringpi库,wiringPi库的pwm配置及使用说明
  10. 切面是异步还是同步操作‘_分布式中采用Logback的MDC机制与AOP切面结合串联日志...
  11. python2.7虚拟环境
  12. UIwebView缩放
  13. html弹窗_对付流氓广告弹窗:彻底告别,这一招最有效
  14. mysql 多个命令行,5.8.2.1在Windows命令行中启动多个MySQL实例
  15. Maxwell安装、配置、脚本制作
  16. windows系统ping端口及利用telnet命令Ping 端口
  17. 腾讯业务安全岗 IDP 谈话总结
  18. 新生儿小名大全:农历三月出生的女孩小名
  19. tensorbook深度学习笔记本电脑
  20. 瑞星误删用友服务文件ServerNT.exe

热门文章

  1. I2C驱动程序框架probe道路
  2. vmware如何安装solaris10
  3. php mysql odbc_PHP Database ODBC
  4. 内存条ar开头的如何看大小_软网推荐:明明白白看内存
  5. 正序 逆序写 java_C語言版和JAVA版 把一個字節正序(高位在前)轉為逆序(低位在前) 和 逆序轉為正序...
  6. python无向加权图_图:无向图(Graph)基本方法及Dijkstra算法的实现 [Python]
  7. 注册表编辑器厘米爱你找不到mysql,win7系统中安装mysql后找不到服务或出现找不到指定文件的解决方法...
  8. php生成zip文件,使用PHP处理zip压缩文件之ZipArchive
  9. java jdk工具
  10. mysql设置最大连接数为200_设置mysql最大连接数的方法