工作中难免会用httpclien进行数据的跨系统传输,这几天老在用,调别的系统的接口,今天就给大家分享出来我用的工具类吧,主要是后期我用的时候可以找到。

package com.cnlive.shenhe.utils;import com.alibaba.fastjson.JSONObject;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.config.RequestConfig.Builder;
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.methods.HttpUriRequest;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;import java.io.*;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.UnsupportedCharsetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;/*** http请求工具类** @author liujiong*/
public class HttpUtil {private Logger logger = LoggerFactory.getLogger(HttpUtil.class);private static PoolingHttpClientConnectionManager pcm;//httpclient连接池private CloseableHttpClient httpClient = null; //http连接private int connectTimeout = 120000;//连接超时时间private int connectionRequestTimeout = 10000;//从连接池获取连接超时时间private int socketTimeout = 300000;//获取数据超时时间private String charset = "utf-8";private RequestConfig requestConfig = null;//请求配置private Builder requestConfigBuilder = null;//build requestConfigprivate List<NameValuePair> nvps = new ArrayList<>();private List<Header> headers = new ArrayList<>();private String requestParam = "";static {pcm = new PoolingHttpClientConnectionManager();pcm.setMaxTotal(50);//整个连接池最大连接数pcm.setDefaultMaxPerRoute(50);//每路由最大连接数,默认值是2}/*** 默认设置** @author Liu Jiong* @createDate 2016年10月30日*/private static HttpUtil defaultInit() {HttpUtil httpUtil = new HttpUtil();if (httpUtil.requestConfig == null) {httpUtil.requestConfigBuilder = RequestConfig.custom().setConnectTimeout(httpUtil.connectTimeout).setConnectionRequestTimeout(httpUtil.connectionRequestTimeout).setSocketTimeout(httpUtil.socketTimeout);httpUtil.requestConfig = httpUtil.requestConfigBuilder.build();}return httpUtil;}/*** 初始化 httpUtil*/public static HttpUtil init() {HttpUtil httpUtil = defaultInit();if (httpUtil.httpClient == null) {httpUtil.httpClient = HttpClients.custom().setConnectionManager(pcm).build();}return httpUtil;}/*** 初始化 httpUtil*/public static HttpUtil init(Map<String, String> paramMap) {HttpUtil httpUtil = init();httpUtil.setParamMap(paramMap);return httpUtil;}/*** 验证初始化*/public static HttpUtil initWithAuth(String ip, int port, String username, String password) {HttpUtil httpUtil = defaultInit();if (httpUtil.httpClient == null) {CredentialsProvider credentialsProvider = new BasicCredentialsProvider();credentialsProvider.setCredentials(new AuthScope(ip, port, AuthScope.ANY_REALM), new UsernamePasswordCredentials(username, password));httpUtil.httpClient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).setConnectionManager(pcm).build();}return httpUtil;}/*** 设置请求头*/public HttpUtil setHeader(String name, String value) {Header header = new BasicHeader(name, value);headers.add(header);return this;}/*** 设置请求头*/public HttpUtil setHeaderMap(Map<String, String> headerMap) {for (Entry<String, String> param : headerMap.entrySet()) {Header header = new BasicHeader(param.getKey(), param.getValue());headers.add(header);}return this;}/*** 设置请求参数*/public HttpUtil setParam(String name, String value) {nvps.add(new BasicNameValuePair(name, value));return this;}/*** 设置请求参数*/public HttpUtil setParamMap(Map<String, String> paramMap) {for (Entry<String, String> param : paramMap.entrySet()) {nvps.add(new BasicNameValuePair(param.getKey(), param.getValue()));}return this;}/*** 设置字符串参数*/public HttpUtil setStringParam(String requestParam) {this.requestParam = requestParam;return this;}/*** 设置连接超时时间*/public HttpUtil setConnectTimeout(int connectTimeout) {this.connectTimeout = connectTimeout;this.requestConfigBuilder = requestConfigBuilder.setConnectTimeout(connectTimeout);requestConfig = requestConfigBuilder.build();return this;}/*** http get 请求*/public Map<String, String> get(String url) {Map<String, String> resultMap = new HashMap<>();//获取请求URIURI uri = getUri(url);if (uri != null) {HttpGet httpGet = new HttpGet(uri);httpGet.setConfig(requestConfig);if (!CollectionUtils.isEmpty(headers)) {Header[] header = new Header[headers.size()];httpGet.setHeaders(headers.toArray(header));}//执行get请求try {CloseableHttpResponse response = httpClient.execute(httpGet);return getHttpResult(response, url, httpGet, resultMap);} catch (Exception e) {httpGet.abort();resultMap.put("result", e.getMessage());logger.error("获取http GET请求返回值失败 url======" + url, e);}}return resultMap;}/*** http post 请求*/public Map<String, String> post(String url) {HttpPost httpPost = new HttpPost(url);httpPost.setConfig(requestConfig);if (!CollectionUtils.isEmpty(headers)) {Header[] header = new Header[headers.size()];httpPost.setHeaders(headers.toArray(header));}if (!CollectionUtils.isEmpty(nvps)) {try {httpPost.setEntity(new UrlEncodedFormEntity(nvps, charset));} catch (UnsupportedEncodingException e) {logger.error("http post entity form error", e);}}if (!StringUtils.isEmpty(requestParam)) {try {httpPost.setEntity(new StringEntity(requestParam, charset));} catch (UnsupportedCharsetException e) {logger.error("http post entity form error", e);}}Map<String, String> resultMap = new HashMap<>();//执行post请求try {CloseableHttpResponse response = httpClient.execute(httpPost);return getHttpResult(response, url, httpPost, resultMap);} catch (Exception e) {httpPost.abort();resultMap.put("result", e.getMessage());logger.error("获取http POST请求返回值失败 url======" + url, e);}return resultMap;}/*** post 上传文件*/public Map<String, String> postUploadFile(String url, Map<String, File> fileParam) {HttpPost httpPost = new HttpPost(url);httpPost.setConfig(requestConfig);if (!CollectionUtils.isEmpty(headers)) {Header[] header = new Header[headers.size()];httpPost.setHeaders(headers.toArray(header));}MultipartEntityBuilder builder = MultipartEntityBuilder.create();if (fileParam != null) {for (Entry<String, File> entry : fileParam.entrySet()) {//将要上传的文件转化为文件流FileBody fileBody = new FileBody(entry.getValue());//设置请求参数builder.addPart(entry.getKey(), fileBody);}}if (!CollectionUtils.isEmpty(nvps)) {for (NameValuePair nvp : nvps) {String value = nvp.getValue();if (!StringUtils.isEmpty(value)) {builder.addTextBody(nvp.getName(), value, ContentType.create("text/plain", charset));}}}httpPost.setEntity(builder.build());Map<String, String> resultMap = new HashMap<>();//执行post请求try {CloseableHttpResponse response = httpClient.execute(httpPost);return getHttpResult(response, url, httpPost, resultMap);} catch (Exception e) {httpPost.abort();resultMap.put("result", e.getMessage());logger.error("获取http postUploadFile 请求返回值失败 url======" + url, e);}return resultMap;}/*** 获取请求返回值*/private Map<String, String> getHttpResult(CloseableHttpResponse response, String url, HttpUriRequest request, Map<String, String> resultMap) {String result = "";int statusCode = response.getStatusLine().getStatusCode();resultMap.put("statusCode", statusCode + "");HttpEntity entity = response.getEntity();if (entity != null) {try {result = EntityUtils.toString(entity, charset);EntityUtils.consume(entity);//释放连接} catch (Exception e) {logger.error("获取http请求返回值解析失败", e);request.abort();}}if (statusCode != 200) {result = "HttpClient status code :" + statusCode + "  request url===" + url;logger.info("HttpClient status code :" + statusCode + "  request url===" + url);request.abort();}resultMap.put("result", result);return resultMap;}/*** 获取重定向url返回的location*/public String redirectLocation(String url) {String location = "";//获取请求URIURI uri = getUri(url);if (uri != null) {HttpGet httpGet = new HttpGet(uri);requestConfig = requestConfigBuilder.setRedirectsEnabled(false).build();//设置自动重定向falsehttpGet.setConfig(requestConfig);if (!CollectionUtils.isEmpty(headers)) {Header[] header = new Header[headers.size()];httpGet.setHeaders(headers.toArray(header));}try {//执行get请求CloseableHttpResponse response = httpClient.execute(httpGet);int statusCode = response.getStatusLine().getStatusCode();if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {//301 302Header header = response.getFirstHeader("Location");if (header != null) {location = header.getValue();}}HttpEntity entity = response.getEntity();if (entity != null) {EntityUtils.consume(entity);}} catch (Exception e) {logger.error("获取http GET请求获取 302 Location失败 url======" + url, e);httpGet.abort();}}return location;}/*** 获取输入流*/public InputStream getInputStream(String url) {//获取请求URIURI uri = getUri(url);if (uri != null) {HttpGet httpGet = new HttpGet(uri);httpGet.setConfig(requestConfig);if (!CollectionUtils.isEmpty(headers)) {Header[] header = new Header[headers.size()];httpGet.setHeaders(headers.toArray(header));}//执行get请求try {CloseableHttpResponse response = httpClient.execute(httpGet);int statusCode = response.getStatusLine().getStatusCode();if (statusCode != 200) {logger.info("HttpClient status code :" + statusCode + "  request url===" + url);httpGet.abort();} else {HttpEntity entity = response.getEntity();if (entity != null) {InputStream in = entity.getContent();return in;}}} catch (Exception e) {logger.error("获取http GET inputStream请求失败 url======" + url, e);httpGet.abort();}}return null;}private URI getUri(String url) {URI uri = null;try {URIBuilder uriBuilder = new URIBuilder(url);if (!CollectionUtils.isEmpty(nvps)) {uriBuilder.setParameters(nvps);}uri = uriBuilder.build();} catch (URISyntaxException e) {logger.error("url 地址异常", e);}return uri;}/*** from请求* @param url* @param params* @return*/public static String form(String url, Map<String, String> params) {URL u = null;HttpURLConnection con = null;// 构建请求参数StringBuffer sb = new StringBuffer();if (params != null) {for (Entry<String, String> e : params.entrySet()) {sb.append(e.getKey());sb.append("=");sb.append(e.getValue());sb.append("&");}sb.substring(0, sb.length() - 1);}// 尝试发送请求try {u = new URL(url);con = (HttpURLConnection) u.openConnection();POST 只能为大写,严格限制,post会不识别con.setRequestMethod("POST");con.setDoOutput(true);con.setDoInput(true);con.setUseCaches(false);con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8");osw.write(sb.toString());osw.flush();osw.close();} catch (Exception e) {e.printStackTrace();} finally {if (con != null) {con.disconnect();}}// 读取返回内容StringBuffer buffer = new StringBuffer();try {//一定要有返回值,否则无法把请求发送给server端。BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));String temp;while ((temp = br.readLine()) != null) {buffer.append(temp);buffer.append("\n");}} catch (Exception e) {e.printStackTrace();}return buffer.toString();}public static void main(String[] args) {/*Map<String, String> map = new HashMap<>();JSONObject param = new JSONObject();param.put("activity_id","60:video:comets:10011#2");param.put("state",3);param.put("attr_tags","");param.put("msg","");map.put("param",param.toJSONString());String form = form("http://yp5ntd.natappfree.cc/CnInteraction/services/commentForHd/auditCallBackNew", map);System.out.println(form);*/JSONObject params = new JSONObject();params.put("video_id","60_8be004799c424688949704814ea0d16d");params.put("state",3+"");params.put("attr_tags","");params.put("msg","");HttpUtil httpUtil = HttpUtil.init();httpUtil.setParam("param",params.toJSONString());String URL ="http://abcd.com/v1/ShenHeInfo/shenheNotify?platform=AUDIT&token=94cead75c";Map<String, String> post = httpUtil.post(URL);System.out.println(post.get("result"));}
}

一个拿来即用的httputil工具类相关推荐

  1. 一个简单易用的Http访问工具类for Android

    前言 去年(2017)参加服务外包省赛的时候,负责App开发的我遇到了一个小难题--Http请求.虽说已经有成熟的HttpUrlConnection库供使用,但依然感到有些不方便:进行一次简单的请求并 ...

  2. 拿来即用,HttpUtil工具类

    HttpUtil工具类 注意低版本有bug.https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient <!- ...

  3. 验证码识别服务器,一个非常好用的验证码识别工具类api接口

    一个非常好用的验证码识别工具类api接口 群发?批量操作?验证码?可能乖孩子对于这些单个有了解,但是对于合在一起就不知道其存在的意义.这个对 于我们日常的生活可能是没有什么用处的,但是对于需要批量检测 ...

  4. 编写一个可动态注入Spring 容器的工具类

    导语   在有些使用场景下,我们使用Bean的时候发现它并没有那么必要在这个类中注入对应的对象引用.就有一个需求,就是再需要的地方将指定的类注入到容器中,这样这个类就可以动态的使用到原本已经在容器中的 ...

  5. 分享一个nodejs中koa操作redis的工具类 基于 ioredis

    分享一个node 操作redis的工具类 基于ioredis redis.js const config = require(':config/server.base.config'); const ...

  6. anychart java实例_结合AnyChart做报表:一个生成AnyChart图形XML数据的工具类

    今天头有点痛,所以不能详细地写了,先把代码贴上来,等身体状况稍微好一点,再继续完善. 1.(主角)一个使用XML模板生成Anychart XML数据的工具类 /** * */ package com. ...

  7. 记录一个使用MD5加密密码的小工具类

    2019独角兽企业重金招聘Python工程师标准>>> package com.zaizai.safty.utils; import java.security.MessageDig ...

  8. Java判断一个字符串中是否包含中文字符工具类

    Java判断一个字符串是否有中文一般情况是利用Unicode编码(CJK统一汉字的编码区间:0x4e00–0x9fbb)的正则来做判断,但是其实这个区间来判断中文不是非常精确,因为有些中文的标点符号比 ...

  9. Springboot 为了偷懒,我封装了一个自适配的数据单位转换工具类

    前言 平时做一些统计数据,经常从数据库或者是从接口获取出来的数据,单位是跟业务需求不一致的. 比如, 我们拿出来的 分, 实际上要是元 又比如,我们拿到的数据需要 乘以100 返回给前端做 百分比展示 ...

最新文章

  1. SQLIOSim 模拟SQLServer的行为来测试IO性能
  2. 成都python数据分析师职业技能_想成为数据分析师,需要重点学习什么技能?
  3. Silverlight 5 新特性
  4. 数据库人员面试:SQL Server常用测试题
  5. Linux文件系统构成
  6. 中国 GDP 20 强城市排行榜(2001-2020)
  7. 高评分防火墙GlassWire:帮你监控、追踪和提升电脑安全
  8. 语义分割——Spatial Pyramid Pooling (SPP)的作用
  9. 如何使用Putty登录安装在VirtualBox里的ubuntu 1
  10. 定义你自己的Logj4 输出,比如 数据库连接池 database connect pool
  11. Python读取指定文件夹下指定类型数据的文件名并保存到TXT文件中
  12. URLSession实现iTunes搜索听歌
  13. Win32反汇编(四)栈的工作原理与堆栈平衡,函数方法参数的调用约定
  14. [UWP开发] Win10微博分享
  15. python sorted方法
  16. DeepLab InvalidArgumentError NodeDef mentions attr dilations not in Op name=Conv2D
  17. 基于微信小程序的驾驶证模拟考试系统的设计与实现
  18. It's a test
  19. matlab计算PN序列的本原多项式
  20. 字蛛fontSpider的使用

热门文章

  1. Html5之formaction属性
  2. win10 1803 频繁死机,卡死不动
  3. (水题 NUPT 1593)8皇后问题(判断是否有元素处于同一行或同一列或同一斜线上)
  4. 别焦虑,好的人生,不慌不忙
  5. html 给视频加音乐,如何给视频添加背景音乐教程
  6. 读书笔记3 《运动饮食1:9》 森拓郎
  7. IOS img图片无法加载显示周围显示边框问题
  8. 计算机运行命令怎么显示不出来,电脑命令窗口怎么打开
  9. linux程序设计中文第4百度云,Linux程序设计中文第4版-有书签.pdf
  10. unity个人版去logo