Http请求封装(对HttpClient类的进一步封装,使之调用更方便。另外,此类管理唯一的HttpClient对象,支持线程池调用,效率更高)

Stella981
• 阅读 447
  1 package com.ad.ssp.engine.common;
  2 
  3 import java.io.IOException;
  4 import java.util.ArrayList;
  5 import java.util.List;
  6 import java.util.Map;
  7 import java.util.Map.Entry;
  8 
  9 import org.apache.http.Header;
 10 import org.apache.http.entity.ByteArrayEntity;
 11 import org.apache.http.entity.ContentType;
 12 import org.apache.http.entity.StringEntity;
 13 import org.apache.http.message.BasicHeader;
 14 import org.apache.logging.log4j.LogManager;
 15 import org.apache.logging.log4j.Logger;
 16 
 17 import com.adwm.lib.http.HttpClient;
 18 import com.adwm.lib.http.HttpResult;
 19 
 20 /**
 21  * 对HttpClient类的进一步封装,使之调用更方便。另外,此类管理唯一的HttpClient对象,支持线程池调用,效率更高
 22  * 
 23  *
 24  */
 25 public class HttpClientUtil {
 26     private static final Logger logger = LogManager.getLogger(HttpClientUtil.class);
 27 
 28 //    private static HttpClient client = new HttpClient(600);
 29     private static HttpClient client = new HttpClient();
 30 
 31     public static HttpClient getInstance() {
 32         return client;
 33     }
 34 
 35     /**
 36      * form方式提交http post请求
 37      * 
 38      * @param targetUrl
 39      *            目标url地址
 40      * @param headers
 41      *            header请求参数集合
 42      * @param postParams
 43      *            body请求参数集合
 44      * @param timeout
 45      *            超时时间(单位为毫秒)
 46      * @return 返回的http body体经utf8编码后的字符串
 47      */
 48     public static String postKVParams1(String targetUrl, Map<String, String> headers, Map<String, Object> postParams,
 49             int timeout) {
 50         List<Header> headerList = getHeaderList(headers);
 51         try {
 52             HttpResult hr = client.post(targetUrl, headerList, postParams, timeout);
 53             if (hr.getStatus() == 200)
 54                 return hr.getContentAsString();
 55             else {
 56                 logger.warn("The request url is: {}, its reponse code is: {}", targetUrl, hr.getStatus());
 57             }
 58         } catch (IOException e) {
 59             // TODO Auto-generated catch block
 60             e.printStackTrace();
 61         }
 62 
 63         return null;
 64     }
 65 
 66     private static List<Header> getHeaderList(Map<String, String> headers) {
 67         if (headers != null && headers.size() > 0) {
 68             List<Header> headerList = new ArrayList<Header>();
 69             for (Entry<String, String> entry : headers.entrySet()) {
 70                 headerList.add(new BasicHeader(entry.getKey(), entry.getValue()));
 71             }
 72             return headerList;
 73         }
 74 
 75         return null;
 76     }
 77 
 78     /**
 79      * form方式提交http post请求
 80      * 
 81      * @param targetUrl
 82      *            目标url地址
 83      * @param headers
 84      *            header请求参数集合
 85      * @param postParams
 86      *            body请求参数集合
 87      * @param timeout
 88      *            超时时间(单位为毫秒)
 89      * @return 未处理的HttpResult对象,供调用方自己解析和处理
 90      */
 91     public static HttpResult postKVParams2(String targetUrl, Map<String, String> headers,
 92             Map<String, Object> postParams, int timeout) {
 93         List<Header> headerList = getHeaderList(headers);
 94         try {
 95             return client.post(targetUrl, headerList, postParams, timeout);
 96         } catch (IOException e) {
 97             // TODO Auto-generated catch block
 98             e.printStackTrace();
 99         }
100 
101         return null;
102     }
103 
104     /**
105      * 用post方法提交json字符串参数
106      * 
107      * @param targetUrl
108      *            目标url地址
109      * @param headers
110      *            header请求参数集合
111      * @param jsonBody
112      *            json字符串
113      * @param timeout
114      *            超时时间(单位为毫秒)
115      * @return 返回的http body体经utf8编码后的字符串
116      */
117     public static String postJsonParams1(String targetUrl, Map<String, String> headers, String jsonBody, int timeout)  throws Exception {
118         List<Header> headerList = getHeaderList(headers);
119         
120         StringEntity entity = new StringEntity(jsonBody, "UTF-8");
121         entity.setContentType("application/json");
122         entity.setContentEncoding("UTF-8");
123         HttpResult httpRst = client.post(targetUrl, headerList, entity, timeout);
124         if(httpRst.getStatus() == ResponseCodeUtil.HTTP_STATUS_OK)
125             return httpRst.getContentAsString();
126         else {
127             logger.warn("The request url is: {}, its reponse code is: {}", targetUrl, httpRst.getStatus());
128         }
129 
130         return null;
131     }
132 
133     /**
134      * 用post方法提交json字符串参数
135      * 
136      * @param targetUrl
137      *            目标url地址
138      * @param headers
139      *            header请求参数集合
140      * @param jsonBody
141      *            json字符串
142      * @param timeout
143      *            超时时间(单位为毫秒)
144      * @return 未处理的HttpResult对象,供调用方自己解析和处理
145      */
146     public static HttpResult postJsonParams2(String targetUrl, Map<String, String> headers, String jsonBody,
147             int timeout)  throws Exception {
148         List<Header> headerList = getHeaderList(headers);
149         StringEntity entity = new StringEntity(jsonBody, "UTF-8");
150         entity.setContentType("application/json");
151         return client.post(targetUrl, headerList, entity, timeout);
152     }
153 
154     /**
155      * 通过POST方式发起protocol请求
156      * @param url
157      * @param headers
158      * @param content
159      * @param timeout
160      * @return
161      */
162     public static byte[] postProtobuf(String url, Map<String, String> headers, byte[] content, int timeout)  throws Exception {
163         List<Header> headerList = getHeaderList(headers);
164         ByteArrayEntity entity = new ByteArrayEntity(content, ContentType.APPLICATION_OCTET_STREAM);
165         HttpResult httpResult = client.post(url, headerList, entity, timeout);
166         if (httpResult.getStatus() == ResponseCodeUtil.HTTP_STATUS_OK){
167             return httpResult.getContent();
168         } else {
169             logger.warn("The request url is: {}, its reponse code is: {}", url, httpResult.getStatus());
170         }
171         return null;
172     }
173 
174     /**
175      * 以get方法请求url
176      * 
177      * @param targetUrl
178      *            目标url地址
179      * @param headers
180      *            header请求参数集合
181      * @param timeout
182      *            超时时间(单位为毫秒)
183      * @return 返回的http body体经utf8编码后的字符串
184      */
185     public static String get1(String targetUrl, Map<String, String> headers, int timeout) throws Exception {
186         List<Header> headerList = getHeaderList(headers);
187         HttpResult httpRst = client.get(targetUrl, headerList, timeout);
188         if(httpRst.getStatus() == ResponseCodeUtil.HTTP_STATUS_OK)
189             return httpRst.getContentAsString();
190         else {
191             logger.warn("The request url is: {}, its reponse code is: {}", targetUrl, httpRst.getStatus());
192         }
193         return null;
194     }
195 
196     /**
197      * 以get方法请求url
198      * 
199      * @param targetUrl
200      *            目标url地址
201      * @param headers
202      *            header请求参数集合
203      * @param timeout
204      *            超时时间(单位为毫秒)
205      * @return 未处理的HttpResult对象,供调用方自己解析和处理
206      */
207     public static HttpResult get2(String targetUrl, Map<String, String> headers, int timeout) throws Exception {
208         List<Header> headerList = getHeaderList(headers);
209         return client.get(targetUrl, headerList, timeout);
210     }
211 
212 }
点赞
收藏
评论区
推荐文章
Wesley13 Wesley13
2年前
java常见的 http 请求库比较
java常见的http请求库有httpclient,RestTemplate,OKhttp,更高层次封装的feign、retrofit1、HttpClientHttpClient:代码复杂,还得操心资源回收等。代码很复杂,冗余代码多,不建议直接使用。2、RestTemplateRestTemplate:是Spring提供的用于访问
Wesley13 Wesley13
2年前
java面试(1)
1.面向对象的基本特征  封装、继承、多态、  封装:把客观事物封装成类  继承:继承一个类,就可以使用这个类的所有功能,并且在无需编写原来类的情况下对这些功能进行扩展  多态:子对象调用父对象,父对象会根据当前调用的子对象以不同的方式运作  实现多态:覆盖,重载2.final\\finally\\finalize的区别  fin
Stella981 Stella981
2年前
HttpClient 连接池配置和使用
在游戏项目开发中,经常会向其它的服务发送一些Http请求,获取一些数据或验证。比如充值,SDK验证等。如果每次都重新创建一个新的HttpClient对象的话,当并发上来时,容易出现异常或连接失败,超时。这里可以使用HttpClient的连接池配置,减少HttpClient创建的数量,减少资源开销。packagecom.mygame.common
Wesley13 Wesley13
2年前
Java 调用RESTful接口的几种方式
前端一般通过Ajax来调用,后端调用的方式还是挺多的,比如HttpURLConnection,HttpClient,Spring的RestTemplate服务端代码如下:服务端接口请求的URL:http://localhost:8080/rest/user/getUser/xiaoming/18(https://www.oschina.net/a
Wesley13 Wesley13
2年前
Java之HttpClient调用WebService接口发送短信源码实战
摘要Java之HttpClient调用WebService接口发送短信源码实战一:接口文档!Java之HttpClient调用WebService接口源码001.png(https://imgblog.csdnimg.cn/img_convert/1e2ea7858d12c11af36e591290ba0496.png)
Easter79 Easter79
2年前
Spring的异步线程处理
Spring封装了JDK的线程池和线程调用,并使用标签就可以开启多线程调用。先进行一个Spring的线程池配置@Configuration@EnableAsyncpublicclassThreadPoolConfigimplementsAsyncConfigurer{@Bean@OverridepublicExecut
Stella981 Stella981
2年前
HttpClient使用总结
<divclass"htmledit\_views"<h1<aname"t0"</a一、使用方法</h1<p使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。<br1.创建HttpClient对象。<br2.创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需
Wesley13 Wesley13
2年前
HttpClient学习 使用 详解
Http协议的重要性相信不用我多说了,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户端发送Http请求变得容易,而且也方便了开发人员测试接口(基于Http协议的),即提高了开发的效率,也方便提高代码的健壮性。因此熟练掌握HttpClient是很重要的必修内容,掌握HttpCl
Stella981 Stella981
2年前
Python基础知识:类
初级篇面向过程:根据业务逻辑从上到下写垒代码函数式:将某功能代码封装到函数中,日后便无需重复编写,仅调用函数即可面向对象:对函数进行分类和封装,让开发“更快更好更强...”1、面向对象三大特性:封装、继承、多态。封装:将内容封装到某处,从某处调用被封装的内容;
liam liam
3个月前
优化你的 JavaScript 项目:Axios request 封装指南
在开发中,为了提高效率,通常对进行封装,简化了请求的发送和对响应的处理。同时,统一错误处理机制有助于维护代码的清晰和一致性。本文介绍了一些高效封装Axios请求的方法。封装理念通过创建一个请求函数,我们可以隐藏Axios的直接调用,将请求的配置作为参数传入