懒羊羊
2024-01-31 e57a8990ae56f657a59c435a0613c5f7a8728003
提交 | 用户 | 时间
e57a89 1 package com.jcdm.common.utils.http;
2
3 import java.io.BufferedReader;
4 import java.io.IOException;
5 import java.io.InputStream;
6 import java.io.InputStreamReader;
7 import java.io.PrintWriter;
8 import java.net.ConnectException;
9 import java.net.SocketTimeoutException;
10 import java.net.URL;
11 import java.net.URLConnection;
12 import java.nio.charset.StandardCharsets;
13 import java.security.cert.X509Certificate;
14 import javax.net.ssl.HostnameVerifier;
15 import javax.net.ssl.HttpsURLConnection;
16 import javax.net.ssl.SSLContext;
17 import javax.net.ssl.SSLSession;
18 import javax.net.ssl.TrustManager;
19 import javax.net.ssl.X509TrustManager;
20 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory;
22 import com.jcdm.common.constant.Constants;
23 import com.jcdm.common.utils.StringUtils;
24
25 /**
26  * 通用http发送方法
27  * 
28  * @author jc
29  */
30 public class HttpUtils
31 {
32     private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);
33
34     /**
35      * 向指定 URL 发送GET方法的请求
36      *
37      * @param url 发送请求的 URL
38      * @return 所代表远程资源的响应结果
39      */
40     public static String sendGet(String url)
41     {
42         return sendGet(url, StringUtils.EMPTY);
43     }
44
45     /**
46      * 向指定 URL 发送GET方法的请求
47      *
48      * @param url 发送请求的 URL
49      * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
50      * @return 所代表远程资源的响应结果
51      */
52     public static String sendGet(String url, String param)
53     {
54         return sendGet(url, param, Constants.UTF8);
55     }
56
57     /**
58      * 向指定 URL 发送GET方法的请求
59      *
60      * @param url 发送请求的 URL
61      * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
62      * @param contentType 编码类型
63      * @return 所代表远程资源的响应结果
64      */
65     public static String sendGet(String url, String param, String contentType)
66     {
67         StringBuilder result = new StringBuilder();
68         BufferedReader in = null;
69         try
70         {
71             String urlNameString = StringUtils.isNotBlank(param) ? url + "?" + param : url;
72             log.info("sendGet - {}", urlNameString);
73             URL realUrl = new URL(urlNameString);
74             URLConnection connection = realUrl.openConnection();
75             connection.setRequestProperty("accept", "*/*");
76             connection.setRequestProperty("connection", "Keep-Alive");
77             connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
78             connection.connect();
79             in = new BufferedReader(new InputStreamReader(connection.getInputStream(), contentType));
80             String line;
81             while ((line = in.readLine()) != null)
82             {
83                 result.append(line);
84             }
85             log.info("recv - {}", result);
86         }
87         catch (ConnectException e)
88         {
89             log.error("调用HttpUtils.sendGet ConnectException, url=" + url + ",param=" + param, e);
90         }
91         catch (SocketTimeoutException e)
92         {
93             log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url + ",param=" + param, e);
94         }
95         catch (IOException e)
96         {
97             log.error("调用HttpUtils.sendGet IOException, url=" + url + ",param=" + param, e);
98         }
99         catch (Exception e)
100         {
101             log.error("调用HttpsUtil.sendGet Exception, url=" + url + ",param=" + param, e);
102         }
103         finally
104         {
105             try
106             {
107                 if (in != null)
108                 {
109                     in.close();
110                 }
111             }
112             catch (Exception ex)
113             {
114                 log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
115             }
116         }
117         return result.toString();
118     }
119
120     /**
121      * 向指定 URL 发送POST方法的请求
122      *
123      * @param url 发送请求的 URL
124      * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
125      * @return 所代表远程资源的响应结果
126      */
127     public static String sendPost(String url, String param)
128     {
129         PrintWriter out = null;
130         BufferedReader in = null;
131         StringBuilder result = new StringBuilder();
132         try
133         {
134             log.info("sendPost - {}", url);
135             URL realUrl = new URL(url);
136             URLConnection conn = realUrl.openConnection();
137             conn.setRequestProperty("accept", "*/*");
138             conn.setRequestProperty("connection", "Keep-Alive");
139             conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
140             conn.setRequestProperty("Accept-Charset", "utf-8");
141             conn.setRequestProperty("contentType", "utf-8");
142             conn.setDoOutput(true);
143             conn.setDoInput(true);
144             out = new PrintWriter(conn.getOutputStream());
145             out.print(param);
146             out.flush();
147             in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
148             String line;
149             while ((line = in.readLine()) != null)
150             {
151                 result.append(line);
152             }
153             log.info("recv - {}", result);
154         }
155         catch (ConnectException e)
156         {
157             log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
158         }
159         catch (SocketTimeoutException e)
160         {
161             log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
162         }
163         catch (IOException e)
164         {
165             log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
166         }
167         catch (Exception e)
168         {
169             log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
170         }
171         finally
172         {
173             try
174             {
175                 if (out != null)
176                 {
177                     out.close();
178                 }
179                 if (in != null)
180                 {
181                     in.close();
182                 }
183             }
184             catch (IOException ex)
185             {
186                 log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
187             }
188         }
189         return result.toString();
190     }
191
192     public static String sendSSLPost(String url, String param)
193     {
194         StringBuilder result = new StringBuilder();
195         String urlNameString = url + "?" + param;
196         try
197         {
198             log.info("sendSSLPost - {}", urlNameString);
199             SSLContext sc = SSLContext.getInstance("SSL");
200             sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());
201             URL console = new URL(urlNameString);
202             HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
203             conn.setRequestProperty("accept", "*/*");
204             conn.setRequestProperty("connection", "Keep-Alive");
205             conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
206             conn.setRequestProperty("Accept-Charset", "utf-8");
207             conn.setRequestProperty("contentType", "utf-8");
208             conn.setDoOutput(true);
209             conn.setDoInput(true);
210
211             conn.setSSLSocketFactory(sc.getSocketFactory());
212             conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
213             conn.connect();
214             InputStream is = conn.getInputStream();
215             BufferedReader br = new BufferedReader(new InputStreamReader(is));
216             String ret = "";
217             while ((ret = br.readLine()) != null)
218             {
219                 if (ret != null && !"".equals(ret.trim()))
220                 {
221                     result.append(new String(ret.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8));
222                 }
223             }
224             log.info("recv - {}", result);
225             conn.disconnect();
226             br.close();
227         }
228         catch (ConnectException e)
229         {
230             log.error("调用HttpUtils.sendSSLPost ConnectException, url=" + url + ",param=" + param, e);
231         }
232         catch (SocketTimeoutException e)
233         {
234             log.error("调用HttpUtils.sendSSLPost SocketTimeoutException, url=" + url + ",param=" + param, e);
235         }
236         catch (IOException e)
237         {
238             log.error("调用HttpUtils.sendSSLPost IOException, url=" + url + ",param=" + param, e);
239         }
240         catch (Exception e)
241         {
242             log.error("调用HttpsUtil.sendSSLPost Exception, url=" + url + ",param=" + param, e);
243         }
244         return result.toString();
245     }
246
247     private static class TrustAnyTrustManager implements X509TrustManager
248     {
249         @Override
250         public void checkClientTrusted(X509Certificate[] chain, String authType)
251         {
252         }
253
254         @Override
255         public void checkServerTrusted(X509Certificate[] chain, String authType)
256         {
257         }
258
259         @Override
260         public X509Certificate[] getAcceptedIssuers()
261         {
262             return new X509Certificate[] {};
263         }
264     }
265
266     private static class TrustAnyHostnameVerifier implements HostnameVerifier
267     {
268         @Override
269         public boolean verify(String hostname, SSLSession session)
270         {
271             return true;
272         }
273     }
274 }