HTTP请求工具类封装

  1 import com.alibaba.fastjson.JSONObject;
  2 import org.apache.http.HttpEntity;
  3 import org.apache.http.client.config.RequestConfig;
  4 import org.apache.http.client.methods.HttpGet;
  5 import org.apache.http.client.methods.HttpPost;
  6 import org.apache.http.client.methods.HttpRequestBase;
  7 import org.apache.http.entity.StringEntity;
  8 import org.apache.http.impl.client.CloseableHttpClient;
  9 import org.apache.http.impl.client.HttpClients;
 10 import org.apache.http.util.EntityUtils;
 11 
 12 import java.io.IOException;
 13 import java.io.UnsupportedEncodingException;
 14 import java.net.URLEncoder;
 15 import java.util.Map;
 16 
 17 /**
 18  * @author
 19  * @description HTTP请求工具类
 20  */
 21 public class HttpUtils {
 22 
 23     /**
 24      * 发送GET请求
 25      *
 26      * @param url         请求URL
 27      * @param queryParams 请求参数
 28      * @return 响应结果
 29      */
 30     public static String doGet(String url, Map<String, Object> queryParams)
 31             throws IOException {
 32         // 拼接参数
 33         if (queryParams != null && !queryParams.isEmpty()) {
 34             url += "?" + urlEncode(queryParams);
 35         }
 36 
 37         // GET请求
 38         HttpGet get = new HttpGet(url);
 39         // 请求配置
 40         get.setConfig(requestConfig());
 41 
 42         // 执行请求
 43         return getResult(get);
 44     }
 45 
 46     /**
 47      * 发送POST请求
 48      *
 49      * @param url        请求URL
 50      * @param bodyParams Body参数
 51      * @return 响应结果
 52      */
 53     public static String doPost(String url, Map<String, Object> bodyParams)
 54             throws IOException {
 55         // POST请求
 56         HttpPost post = new HttpPost(url);
 57         // 设置Body参数
 58         setBodyParams(post, bodyParams);
 59         // 请求配置
 60         post.setConfig(requestConfig());
 61 
 62         // 执行请求
 63         return getResult(post);
 64     }
 65 
 66     /**
 67      * 发送带Header的GET请求
 68      *
 69      * @param url         请求URL
 70      * @param headers     请求头
 71      * @param queryParams 查询参数
 72      * @return 响应结果
 73      */
 74     public static String doGet(String url, Map<String, String> headers, Map<String, Object> queryParams)
 75             throws IOException {
 76         // 拼接参数
 77         if (queryParams != null && !queryParams.isEmpty()) {
 78             url += "?" + urlEncode(queryParams);
 79         }
 80 
 81         // GET请求
 82         HttpGet get = new HttpGet(url);
 83         // 设置请求头
 84         setHeaders(get, headers);
 85         // 请求配置
 86         get.setConfig(requestConfig());
 87 
 88         // 执行请求
 89         return getResult(get);
 90     }
 91 
 92     /**
 93      * 发送带Header的POST请求
 94      *
 95      * @param url        请求URL
 96      * @param headers    请求头
 97      * @param bodyParams Body参数
 98      * @return 响应结果
 99      */
100     public static String doPost(String url, Map<String, String> headers, Map<String, Object> bodyParams)
101             throws IOException {
102         // POST请求
103         HttpPost post = new HttpPost(url);
104         // 设置请求头
105         setHeaders(post, headers);
106         // 设置Body参数
107         setBodyParams(post, bodyParams);
108         // 请求配置
109         post.setConfig(requestConfig());
110 
111         // 执行请求
112         return getResult(post);
113     }
114 
115     /**
116      * 执行HTTP请求
117      *
118      * @param requestBase HTTP请求
119      * @return 响应结果
120      */
121     private static String getResult(HttpRequestBase requestBase)
122             throws IOException {
123         // HTTP客户端
124         CloseableHttpClient httpClient = HttpClients.createDefault();
125 
126         // 响应结果
127         String result = EntityUtils.toString(httpClient.execute(requestBase).getEntity());
128         httpClient.close();
129 
130         // 返回响应结果
131         return result;
132     }
133 
134     /**
135      * 请求配置
136      *
137      * @return 请求配置
138      */
139     private static RequestConfig requestConfig() {
140         return RequestConfig
141                 .custom()
142                 // 连接主机超时时间
143                 .setConnectTimeout(35000)
144                 // 请求超时时间
145                 .setConnectionRequestTimeout(35000)
146                 // 数据读取超时时间
147                 .setSocketTimeout(60000)
148                 .build();
149     }
150 
151     /**
152      * 设置请求头
153      *
154      * @param requestBase HTTP请求
155      * @param headers     请求头
156      */
157     private static void setHeaders(HttpRequestBase requestBase, Map<String, String> headers) {
158         // 设置请求头
159         if (headers != null && !headers.isEmpty()) {
160             for (Map.Entry<String, String> entry : headers.entrySet()) {
161                 requestBase.setHeader(entry.getKey(), entry.getValue());
162             }
163         }
164     }
165 
166     /**
167      * URL参数编码
168      *
169      * @param queryParams 请求参数
170      * @return 参数编码结果
171      */
172     private static String urlEncode(Map<?, ?> queryParams)
173             throws UnsupportedEncodingException {
174         StringBuilder sb = new StringBuilder();
175         for (Map.Entry<?, ?> entry : queryParams.entrySet()) {
176             if (sb.length() > 0) {
177                 sb.append("&");
178             }
179             sb.append(String.format("%s=%s",
180                     URLEncoder.encode(entry.getKey().toString(), "UTF-8"),
181                     URLEncoder.encode(entry.getValue().toString(), "UTF-8")
182             ));
183         }
184         return sb.toString();
185     }
186 
187     /**
188      * 设置Body参数
189      *
190      * @param post       POST请求
191      * @param bodyParams Body参数
192      */
193     private static void setBodyParams(HttpPost post, Map<?, ?> bodyParams)
194             throws UnsupportedEncodingException {
195         HttpEntity entity = new StringEntity(JSONObject.toJSONString(bodyParams));
196         post.setEntity(entity);
197     }
198 
199 }
posted @ 2020-12-06 13:45  SnowQiQi  阅读(603)  评论(0编辑  收藏  举报