Java发送http/https请求工具类之Jsoup

引入maven依赖

<dependency>
    <groupId>org.jsoup</groupId>
    <artifactId>jsoup</artifactId>
    <version>1.11.3</version>
</dependency>

HttpUtil.java

  1 package com.zhl.common.utils;
  2 
  3 import org.jsoup.Connection;
  4 import org.jsoup.Connection.Method;
  5 import org.jsoup.Connection.Response;
  6 import org.jsoup.Jsoup;
  7 
  8 import javax.net.ssl.*;
  9 import java.io.*;
 10 import java.security.SecureRandom;
 11 import java.security.cert.CertificateException;
 12 import java.security.cert.X509Certificate;
 13 import java.util.ArrayList;
 14 import java.util.List;
 15 import java.util.Map;
 16 
 17 /**
 18  * Http发送post请求工具,兼容http和https两种请求类型
 19  */
 20 public class HttpUtil {
 21 
 22     /**
 23      * 请求超时时间 10s
 24      */
 25     private static final int TIME_OUT = 10000;
 26 
 27     /**
 28      * Https请求
 29      */
 30     private static final String HTTPS = "https";
 31 
 32     /**
 33      * Content-Type
 34      */
 35     private static final String CONTENT_TYPE = "Content-Type";
 36 
 37     /**
 38      * 表单提交方式Content-Type
 39      */
 40     private static final String FORM_TYPE = "application/x-www-form-urlencoded;charset=UTF-8";
 41 
 42     /**
 43      * JSON提交方式Content-Type
 44      */
 45     private static final String JSON_TYPE = "application/json;charset=UTF-8";
 46 
 47     /**
 48      * 发送Get请求
 49      * 
 50      * @param url
 51      *            请求URL
 52      * @return HTTP响应对象
 53      * @throws IOException
 54      *             程序异常时抛出,由调用者处理
 55      */
 56     public static Response get(String url) throws IOException {
 57         return get(url, null);
 58     }
 59 
 60     /**
 61      * 发送Get请求
 62      * 
 63      * @param url
 64      *            请求URL
 65      * @param headers
 66      *            请求头参数
 67      * @return HTTP响应对象
 68      * @throws IOException
 69      *             程序异常时抛出,由调用者处理
 70      */
 71     public static Response get(String url, Map<String, String> headers) throws IOException {
 72         if (null == url || url.isEmpty()) {
 73             throw new RuntimeException("The request URL is blank.");
 74         }
 75 
 76         // 如果是Https请求
 77         if (url.startsWith(HTTPS)) {
 78             getTrust();
 79         }
 80         Connection connection = Jsoup.connect(url);
 81         connection.method(Method.GET);
 82         connection.timeout(TIME_OUT);
 83         connection.ignoreHttpErrors(true);
 84         connection.ignoreContentType(true);
 85         
 86         if (null != headers) {
 87             connection.headers(headers);
 88         }
 89 
 90         Response response = connection.execute();
 91         return response;
 92     }
 93 
 94     /**
 95      * 发送JSON格式参数POST请求
 96      * 
 97      * @param url
 98      *            请求路径
 99      * @param params
100      *            JSON格式请求参数
101      * @return HTTP响应对象
102      * @throws IOException
103      *             程序异常时抛出,由调用者处理
104      */
105     public static Response post(String url, String params) throws IOException {
106         return doPostRequest(url, null, params);
107     }
108 
109     /**
110      * 发送JSON格式参数POST请求
111      * 
112      * @param url
113      *            请求路径
114      * @param headers
115      *            请求头中设置的参数
116      * @param params
117      *            JSON格式请求参数
118      * @return HTTP响应对象
119      * @throws IOException
120      *             程序异常时抛出,由调用者处理
121      */
122     public static Response post(String url, Map<String, String> headers, String params) throws IOException {
123         return doPostRequest(url, headers, params);
124     }
125 
126     /**
127      * 字符串参数post请求
128      * 
129      * @param url
130      *            请求URL地址
131      * @param paramMap
132      *            请求字符串参数集合
133      * @return HTTP响应对象
134      * @throws IOException
135      *             程序异常时抛出,由调用者处理
136      */
137     public static Response post(String url, Map<String, String> paramMap) throws IOException {
138         return doPostRequest(url, null, paramMap, null);
139     }
140 
141     /**
142      * 带请求头的普通表单提交方式post请求
143      * 
144      * @param headers
145      *            请求头参数
146      * @param url
147      *            请求URL地址
148      * @param paramMap
149      *            请求字符串参数集合
150      * @return HTTP响应对象
151      * @throws IOException
152      *             程序异常时抛出,由调用者处理
153      */
154     public static Response post(Map<String, String> headers, String url, Map<String, String> paramMap)
155             throws IOException {
156         return doPostRequest(url, headers, paramMap, null);
157     }
158 
159     /**
160      * 带上传文件的post请求
161      * 
162      * @param url
163      *            请求URL地址
164      * @param paramMap
165      *            请求字符串参数集合
166      * @param fileMap
167      *            请求文件参数集合
168      * @return HTTP响应对象
169      * @throws IOException
170      *             程序异常时抛出,由调用者处理
171      */
172     public static Response post(String url, Map<String, String> paramMap, Map<String, File> fileMap)
173             throws IOException {
174         return doPostRequest(url, null, paramMap, fileMap);
175     }
176 
177     /**
178      * 带请求头的上传文件post请求
179      * 
180      * @param url
181      *            请求URL地址
182      * @param headers
183      *            请求头参数
184      * @param paramMap
185      *            请求字符串参数集合
186      * @param fileMap
187      *            请求文件参数集合
188      * @return HTTP响应对象
189      * @throws IOException
190      *             程序异常时抛出,由调用者处理
191      */
192     public static Response post(String url, Map<String, String> headers, Map<String, String> paramMap,
193             Map<String, File> fileMap) throws IOException {
194         return doPostRequest(url, headers, paramMap, fileMap);
195     }
196 
197     /**
198      * 执行post请求
199      * 
200      * @param url
201      *            请求URL地址
202      * @param headers
203      *            请求头
204      * @param jsonParams
205      *            请求JSON格式字符串参数
206      * @return HTTP响应对象
207      * @throws IOException
208      *             程序异常时抛出,由调用者处理
209      */
210     private static Response doPostRequest(String url, Map<String, String> headers, String jsonParams)
211             throws IOException {
212         if (null == url || url.isEmpty()) {
213             throw new RuntimeException("The request URL is blank.");
214         }
215 
216         // 如果是Https请求
217         if (url.startsWith(HTTPS)) {
218             getTrust();
219         }
220 
221         Connection connection = Jsoup.connect(url);
222         connection.method(Method.POST);
223         connection.timeout(TIME_OUT);
224         connection.ignoreHttpErrors(true);
225         connection.ignoreContentType(true);
226         connection.maxBodySize(0);
227 
228         if (null != headers) {
229             connection.headers(headers);
230         }
231 
232         connection.header(CONTENT_TYPE, JSON_TYPE);
233         connection.requestBody(jsonParams);
234 
235         Response response = connection.execute();
236         return response;
237     }
238 
239     /**
240      * 普通表单方式发送POST请求
241      * 
242      * @param url
243      *            请求URL地址
244      * @param headers
245      *            请求头
246      * @param paramMap
247      *            请求字符串参数集合
248      * @param fileMap
249      *            请求文件参数集合
250      * @return HTTP响应对象
251      * @throws IOException
252      *             程序异常时抛出,由调用者处理
253      */
254     private static Response doPostRequest(String url, Map<String, String> headers, Map<String, String> paramMap,
255             Map<String, File> fileMap) throws IOException {
256         if (null == url || url.isEmpty()) {
257             throw new RuntimeException("The request URL is blank.");
258         }
259 
260         // 如果是Https请求
261         if (url.startsWith(HTTPS)) {
262             getTrust();
263         }
264 
265         Connection connection = Jsoup.connect(url);
266         connection.method(Method.POST);
267         connection.timeout(TIME_OUT);
268         connection.ignoreHttpErrors(true);
269         connection.ignoreContentType(true);
270         connection.maxBodySize(0);
271 
272         if (null != headers) {
273             connection.headers(headers);
274         }
275 
276         // 收集上传文件输入流,最终全部关闭
277         List<InputStream> inputStreamList = null;
278         try {
279             // 添加文件参数
280             if (null != fileMap && !fileMap.isEmpty()) {
281                 inputStreamList = new ArrayList<InputStream>();
282                 InputStream in = null;
283                 File file = null;
284 
285                 for (Map.Entry<String, File> e : fileMap.entrySet()) {
286                     file = e.getValue();
287                     in = new FileInputStream(file);
288                     inputStreamList.add(in);
289                     connection.data(e.getKey(), file.getName(), in);
290                 }
291             }
292 
293             // 普通表单提交方式
294             else {
295                 connection.header(CONTENT_TYPE, FORM_TYPE);
296             }
297 
298             // 添加字符串类参数
299             if (null != paramMap && !paramMap.isEmpty()) {
300                 connection.data(paramMap);
301             }
302 
303             Response response = connection.execute();
304             return response;
305         }
306 
307         // 关闭上传文件的输入流
308         finally {
309             closeStream(inputStreamList);
310         }
311     }
312 
313     /**
314      * 关流
315      * 
316      * @param streamList
317      *            流集合
318      */
319     private static void closeStream(List<? extends Closeable> streamList) {
320         if (null != streamList) {
321             for (Closeable stream : streamList) {
322                 try {
323                     stream.close();
324                 } catch (IOException e) {
325                     e.printStackTrace();
326                 }
327             }
328         }
329     }
330 
331     /**
332      * 获取服务器信任
333      */
334     private static void getTrust() {
335         try {
336             HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
337                 public boolean verify(String hostname, SSLSession session) {
338                     return true;
339                 }
340             });
341             SSLContext context = SSLContext.getInstance("TLS");
342             context.init(null, new X509TrustManager[] { new X509TrustManager() {
343                 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
344                 }
345                 public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
346                 }
347                 public X509Certificate[] getAcceptedIssuers() {
348                     return new X509Certificate[0];
349                 }
350             } }, new SecureRandom());
351             HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
352         } catch (Exception e) {
353             e.printStackTrace();
354         }
355     }
356 
357 }

 

posted @ 2020-05-26 11:25  渭城西去客  阅读(684)  评论(0)    收藏  举报