Http、Https请求工具类

最近在做微信开发,使用http调用第三方服务API,有些是需要https协议,通过资料和自己编码,写了个支持http和https的工具类,经验证可用,现贴出来保留,也供需要的人使用(有不足的地方,也请大家指教):

  1 import java.io.BufferedReader;
  2 import java.io.InputStream;
  3 import java.io.InputStreamReader;
  4 import java.io.OutputStream;
  5 import java.net.HttpURLConnection;
  6 import java.net.URL;
  7 import java.net.URLEncoder;
  8 import java.util.Map;
  9 import java.util.Map.Entry;
 10 
 11 import javax.net.ssl.HostnameVerifier;
 12 import javax.net.ssl.HttpsURLConnection;
 13 import javax.net.ssl.SSLContext;
 14 import javax.net.ssl.SSLSession;
 15 import javax.net.ssl.SSLSocketFactory;
 16 import javax.net.ssl.TrustManager;
 17 
 18 import org.springframework.util.StringUtils;
 19 
 20 /**
 21  * http、https 请求工具类, 微信为https的请求
 22  * @author yehx
 23  *
 24  */
 25 public class HttpUtil {
 26 
 27     private static final String DEFAULT_CHARSET = "UTF-8";
 28 
 29     private static final String _GET = "GET"; // GET
 30     private static final String _POST = "POST";// POST
 31     public static final int DEF_CONN_TIMEOUT = 30000;
 32     public static final int DEF_READ_TIMEOUT = 30000;
 33 
 34     /**
 35      * 初始化http请求参数
 36      * 
 37      * @param url
 38      * @param method
 39      * @param headers
 40      * @return
 41      * @throws Exception
 42      */
 43     private static HttpURLConnection initHttp(String url, String method,
 44             Map<String, String> headers) throws Exception {
 45         URL _url = new URL(url);
 46         HttpURLConnection http = (HttpURLConnection) _url.openConnection();
 47         // 连接超时
 48         http.setConnectTimeout(DEF_CONN_TIMEOUT);
 49         // 读取超时 --服务器响应比较慢,增大时间
 50         http.setReadTimeout(DEF_READ_TIMEOUT);
 51         http.setUseCaches(false);
 52         http.setRequestMethod(method);
 53         http.setRequestProperty("Content-Type",
 54                 "application/x-www-form-urlencoded");
 55         http.setRequestProperty(
 56                 "User-Agent",
 57                 "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
 58         if (null != headers && !headers.isEmpty()) {
 59             for (Entry<String, String> entry : headers.entrySet()) {
 60                 http.setRequestProperty(entry.getKey(), entry.getValue());
 61             }
 62         }
 63         http.setDoOutput(true);
 64         http.setDoInput(true);
 65         http.connect();
 66         return http;
 67     }
 68 
 69     /**
 70      * 初始化http请求参数
 71      * 
 72      * @param url
 73      * @param method
 74      * @return
 75      * @throws Exception
 76      */
 77     private static HttpsURLConnection initHttps(String url, String method,
 78             Map<String, String> headers) throws Exception {
 79         TrustManager[] tm = { new MyX509TrustManager() };
 80         System.setProperty("https.protocols", "TLSv1");
 81         SSLContext sslContext = SSLContext.getInstance("TLS");
 82         sslContext.init(null, tm, new java.security.SecureRandom());
 83         // 从上述SSLContext对象中得到SSLSocketFactory对象
 84         SSLSocketFactory ssf = sslContext.getSocketFactory();
 85         URL _url = new URL(url);
 86         HttpsURLConnection http = (HttpsURLConnection) _url.openConnection();
 87         // 设置域名校验
 88         http.setHostnameVerifier(new HttpUtil().new TrustAnyHostnameVerifier());
 89         // 连接超时
 90         http.setConnectTimeout(DEF_CONN_TIMEOUT);
 91         // 读取超时 --服务器响应比较慢,增大时间
 92         http.setReadTimeout(DEF_READ_TIMEOUT);
 93         http.setUseCaches(false);
 94         http.setRequestMethod(method);
 95         http.setRequestProperty("Content-Type",
 96                 "application/x-www-form-urlencoded");
 97         http.setRequestProperty(
 98                 "User-Agent",
 99                 "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
100         if (null != headers && !headers.isEmpty()) {
101             for (Entry<String, String> entry : headers.entrySet()) {
102                 http.setRequestProperty(entry.getKey(), entry.getValue());
103             }
104         }
105         http.setSSLSocketFactory(ssf);
106         http.setDoOutput(true);
107         http.setDoInput(true);
108         http.connect();
109         return http;
110     }
111 
112     /**
113      * 
114      * @description 功能描述: get 请求
115      * @return 返回类型:
116      * @throws Exception
117      */
118     public static String get(String url, Map<String, String> params,
119             Map<String, String> headers) throws Exception {
120         HttpURLConnection http = null;
121         if (isHttps(url)) {
122             http = initHttps(initParams(url, params), _GET, headers);
123         } else {
124             http = initHttp(initParams(url, params), _GET, headers);
125         }
126         InputStream in = http.getInputStream();
127         BufferedReader read = new BufferedReader(new InputStreamReader(in,
128                 DEFAULT_CHARSET));
129         String valueString = null;
130         StringBuffer bufferRes = new StringBuffer();
131         while ((valueString = read.readLine()) != null) {
132             bufferRes.append(valueString);
133         }
134         in.close();
135         if (http != null) {
136             http.disconnect();// 关闭连接
137         }
138         return bufferRes.toString();
139     }
140 
141     public static String get(String url) throws Exception {
142         return get(url, null);
143     }
144 
145     public static String get(String url, Map<String, String> params)
146             throws Exception {
147         return get(url, params, null);
148     }
149 
150     public static String post(String url, String params)
151             throws Exception {
152         HttpURLConnection http = null;
153         if (isHttps(url)) {
154             http = initHttps(url, _POST, null);
155         } else {
156             http = initHttp(url, _POST, null);
157         }
158         OutputStream out = http.getOutputStream();
159         out.write(params.getBytes(DEFAULT_CHARSET));
160         out.flush();
161         out.close();
162 
163         InputStream in = http.getInputStream();
164         BufferedReader read = new BufferedReader(new InputStreamReader(in,
165                 DEFAULT_CHARSET));
166         String valueString = null;
167         StringBuffer bufferRes = new StringBuffer();
168         while ((valueString = read.readLine()) != null) {
169             bufferRes.append(valueString);
170         }
171         in.close();
172         if (http != null) {
173             http.disconnect();// 关闭连接
174         }
175         return bufferRes.toString();
176     }
177 
178     /**
179      * 功能描述: 构造请求参数
180      * 
181      * @return 返回类型:
182      * @throws Exception
183      */
184     public static String initParams(String url, Map<String, String> params)
185             throws Exception {
186         if (null == params || params.isEmpty()) {
187             return url;
188         }
189         StringBuilder sb = new StringBuilder(url);
190         if (url.indexOf("?") == -1) {
191             sb.append("?");
192         }
193         sb.append(map2Url(params));
194         return sb.toString();
195     }
196 
197     /**
198      * map构造url
199      * 
200      * @return 返回类型:
201      * @throws Exception
202      */
203     public static String map2Url(Map<String, String> paramToMap)
204             throws Exception {
205         if (null == paramToMap || paramToMap.isEmpty()) {
206             return null;
207         }
208         StringBuffer url = new StringBuffer();
209         boolean isfist = true;
210         for (Entry<String, String> entry : paramToMap.entrySet()) {
211             if (isfist) {
212                 isfist = false;
213             } else {
214                 url.append("&");
215             }
216             url.append(entry.getKey()).append("=");
217             String value = entry.getValue();
218             if (!StringUtils.isEmpty(value)) {
219                 url.append(URLEncoder.encode(value, DEFAULT_CHARSET));
220             }
221         }
222         return url.toString();
223     }
224 
225     /**
226      * 检测是否https
227      * 
228      * @param url
229      */
230     private static boolean isHttps(String url) {
231         return url.startsWith("https");
232     }
233 
234     /**
235      * https 域名校验
236      * 
237      * @param url
238      * @param params
239      * @return
240      */
241     public class TrustAnyHostnameVerifier implements HostnameVerifier {
242         public boolean verify(String hostname, SSLSession session) {
243             return true;// 直接返回true
244         }
245     }
246 }

 

posted @ 2016-08-24 12:37  yehx  阅读(22072)  评论(3编辑  收藏  举报