后台开发经常会调用第三方的接口,整理一个HttpUtils,以后用到直接copy....

package com.yfq360.yfq.util;import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
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.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;public final class HttpUtils {private static Logger logger = LoggerFactory.getLogger(HttpUtils.class);/*** @param getUrl     请求地址* @param params 提交的请求参数*/public static String get(String getUrl, Map<String, String> params) {return get(getUrl, params, "UTF-8");}public static String get(String getUrl, Map<String, String> params, String charset) {return get(getUrl, charset, map2NameValuePair(params));}public static String get(String getUrl, NameValuePair... parameters) {return get(getUrl, "UTF-8", parameters);}public static String get(String getUrl, String charset, NameValuePair... parameters) {return get(getUrl, 10000, 30000, charset, parameters);}public static String get(String url, int connTimeout, int soTimeout, String charset, NameValuePair... parameters) {if (StringUtils.isBlank(url)) {throw new IllegalArgumentException("get请求地址不能为空");} else {GetMethod httpGet = null;String respTxt = null;try {HttpClient httpClient = new HttpClient();HttpConnectionManagerParams httpConnectionManagerParams = httpClient.getHttpConnectionManager().getParams();httpConnectionManagerParams.setConnectionTimeout(connTimeout);httpConnectionManagerParams.setSoTimeout(soTimeout);httpGet = new GetMethod(url);httpGet.setRequestHeader("Content-Type", "text/html;charset=" + charset);if (null != parameters && parameters.length > 0) {httpGet.setQueryString(parameters);}int respCode = httpClient.executeMethod(httpGet);if (respCode == HttpStatus.SC_OK) {respTxt = httpGet.getResponseBodyAsString();}} catch (Exception e) {logger.error(String.format("HttpUtils.get:httpGet请求发生异常:地址:%s, parameters:%s", url, parameters == null ? null : JsonUtils.toJson(parameters)), e);} finally {if (httpGet != null)httpGet.releaseConnection();}return respTxt;}}public static String post(String postUrl, Map<String, String> params) {return post(postUrl, params, "UTF-8");}public static String post(String postUrl, Map<String, String> params, String charset) {return post(postUrl, charset, map2NameValuePair(params));}public static String post(String postUrl, NameValuePair... parameters) {return post(postUrl, "UTF-8", parameters);}public static String post(String postUrl, String charset, NameValuePair... parameters) {return post(postUrl, 10000, 30000, charset, parameters);}public static String post(String postUrl, int connTimeout, int soTimeout, String charset, NameValuePair... parameters) {PostMethod httpPost = null;String respTxt = null;try {HttpClient httpClient = new HttpClient();HttpConnectionManagerParams httpConnectionManagerParams = httpClient.getHttpConnectionManager().getParams();httpConnectionManagerParams.setConnectionTimeout(connTimeout);httpConnectionManagerParams.setSoTimeout(soTimeout);httpPost = new PostMethod(postUrl);httpPost.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, charset);if (parameters != null && parameters.length > 0) {httpPost.addParameters(parameters);}int respCode = httpClient.executeMethod(httpPost);if (respCode == HttpStatus.SC_OK) {respTxt = httpPost.getResponseBodyAsString();}} catch (Exception ex) {logger.error(String.format("HttpUtils.post:httpPost请求发生异常:地址:%s, parameters:%s", postUrl, parameters), ex);} finally {if (httpPost != null)httpPost.releaseConnection();}return respTxt;}public static String postWithBody(String postUrl, int connTimeout, int soTimeout, RequestEntity requestEntity) {return postWithBody(postUrl, connTimeout, soTimeout, requestEntity, false);}public static String postWithBody(String postUrl, int connTimeout, int soTimeout, RequestEntity requestEntity, boolean isHttps, Header... headers) {PostMethod httpPost = null;String respTxt = null;try {if(isHttps){Protocol https = new Protocol("https", new HTTPSSecureProtocolSocketFactory(), 443);Protocol.registerProtocol("https", https);}HttpClient httpClient = new HttpClient();HttpConnectionManagerParams httpConnectionManagerParams = httpClient.getHttpConnectionManager().getParams();httpConnectionManagerParams.setConnectionTimeout(connTimeout);httpConnectionManagerParams.setSoTimeout(soTimeout);httpPost = new PostMethod(postUrl);httpPost.setRequestEntity(requestEntity);if(headers != null) {for (int i = 0; i < headers.length; i++) {httpPost.addRequestHeader(headers[i]);}}int respCode = httpClient.executeMethod(httpPost);if (respCode == HttpStatus.SC_OK) {respTxt = httpPost.getResponseBodyAsString();}else{logger.error("HttpUtils.postWithBody: 请求失败, 地址:{}, parameters:{}, HttpStatus: {}", postUrl, requestEntity, respCode);}} catch (Exception ex) {logger.error(String.format("HttpUtils.postWithBody:httpPost请求发生异常:地址:%s, parameters:%s", postUrl, requestEntity), ex);} finally {if (httpPost != null)httpPost.releaseConnection();if(isHttps){Protocol.unregisterProtocol("https");}}return respTxt;}public static boolean isFromMobile(HttpServletRequest request) {String userAgent = request.getHeader("user-agent");return isFromMobile(userAgent);}public static boolean isFromMobile(String userAgent) {return userAgent.toLowerCase().matches(".+(iphone|ipod|android|ios|ipad).+");}private static NameValuePair[] map2NameValuePair(Map<String, String> params){NameValuePair[] parameters = null;if(params != null && params.size() > 0){parameters = new NameValuePair[params.size()];int i = 0;for (Map.Entry<String, String> entry : params.entrySet()) {parameters[i++] = new NameValuePair(entry.getKey(), entry.getValue());}}return parameters;}public static String postBusiBody(String postUrl, int connTimeout, int soTimeout, String charset, JSONObject json) {RequestConfig defaultRequestConfig = RequestConfig.custom() .setSocketTimeout(soTimeout) .setConnectTimeout(connTimeout).setConnectionRequestTimeout(connTimeout).setStaleConnectionCheckEnabled(true).build();CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();HttpPost post = new HttpPost(postUrl);String paramsStr = json.toString().replaceAll("\\\\\\\\", "\\\\");StringEntity myEntity = new StringEntity(paramsStr,charset);// 构造请求数据myEntity.setContentType("application/json");post.setEntity(myEntity);// 设置请求体String responseContent = null; // 响应内容CloseableHttpResponse response = null;try {response = client.execute(post);if (response.getStatusLine().getStatusCode() == 200) {HttpEntity entity = response.getEntity();responseContent = EntityUtils.toString(entity, charset);}} catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {if (response != null)response.close();} catch (IOException e) {e.printStackTrace();} finally {try {if (client != null)client.close();} catch (IOException e) {e.printStackTrace();}}}return responseContent; }public static String post(String postUrl,String charset,JSONObject json) {return postBusiBody(postUrl,10000,10000,charset,json);}}

HttpUtils http请求工具类相关推荐

  1. Java 常用HTTP请求工具类HttpUtils

    .pom依赖 <!-- httpclient --><dependency><groupId>org.apache.httpcomponents</group ...

  2. HTTP POST 请求工具类

    HTTP/HTTPS POST 请求工具类 Maven pom.xml 引入依赖 <dependency><groupId>org.apache.httpcomponents& ...

  3. 【Http请求工具类】

    Http请求工具类(待优化) 添加相关依赖 <!-- 发送http请求依赖 --><dependency><groupId>commons-io</group ...

  4. .NET WebApi调用微信接口Https请求工具类

    .NET WebApi调用微信接口Https请求工具类 using System; using System.Collections.Generic; using System.IO; using S ...

  5. HTTP请求工具类(POST)

    HTTP请求工具类    POST请求 package com.cuierdan.utils;import org.apache.logging.log4j.LogManager; import or ...

  6. Http请求工具类:Get/Post

    第一种 import com.alibaba.fastjson.JSONObject; import org.apache.http.HttpEntity; import org.apache.htt ...

  7. C#实现的UDP收发请求工具类实例

    本文实例讲述了C#实现的UDP收发请求工具类.分享给大家供大家参考,具体如下: 初始化: ListeningPort = int.Parse(ConfigurationManager.AppSetti ...

  8. 【Java】HTTP请求工具类

    前言 在工作中可能存在要去调用其他项目的接口,这篇文章我们实现在Java代码中实现调用其他项目的接口. 本章内容: 创建一个携带参数的POST请求,去请求其他项目的接口并返回数据. 附加HTTP请求工 ...

  9. http和https请求工具类

    https请求 @Slf4j public class HttpPostUtils {public static int RESPONSE_STATUS_OK = 0;public static JS ...

最新文章

  1. [PyTorch] rnn,lstm,gru中输入输出维度
  2. 笔记 - ES6 - 学前浅析
  3. [vSphere培训实录]利用模板部署虚拟机时的一个小错误
  4. 【Codeforces Round #767 (Div. 2)】 C. Meximum Array 题解
  5. 201521123060 《Java程序设计》第10周学习总结
  6. 离线轻量级大数据平台Spark之JavaRDD关联join操作
  7. Leetcode 153. 寻找旋转排序数组中的最小值 解题思路及C++实现
  8. 在python中查看关键字、需要执行_python关键字以及含义,用法
  9. centos7输入法,非root用户无法使用
  10. Spring Boot文档阅读笔记-Spring Boot @Bean解析
  11. 超2亿学生集体上线 在线教育概念股齐飞
  12. CPU位数、操作系统位数、应用程序位数浅析
  13. 梯度下降法and实战
  14. MCTS顺利通过,下一步MCPD
  15. Cocos2d-x学习之 整体框架描述
  16. 数据库优化之MySQL
  17. Android开发入门案例
  18. deepnode软件下载地址_天正软件全套安装包下载地址
  19. 入门级测试Kotlin实现PopWindow弹窗代码
  20. 项目经理怎么写周总结和周计划?

热门文章

  1. unity 清理项目中的多余资源
  2. java将字符串分段输出_java输入字符串并将每个字符输出的方法
  3. 一周碎碎念,2021.10.31,重启跑步
  4. 如何小成本实现私域线索3倍增长?| 最佳实践
  5. 「我有一剑可开天门」大厂面试真题,这边建议是直接开冲
  6. WebStudy-CSS学习2
  7. 第三讲 html超链接和表格形式
  8. 新手如何画出自定义View(Android——自定义折线图)
  9. keil与source insght项目重命名
  10. ccxprocess启动项可以禁用么_Mac使用技巧:提高系统运行速度 可以禁止Adobe自启动...