[Java] HttpURLConnection类 封装

  1 package com.xiwi;
  2 import java.io.BufferedReader;
  3 import java.io.IOException;
  4 import java.io.InputStreamReader;
  5 import java.io.OutputStreamWriter;
  6 import java.net.HttpURLConnection;
  7 import java.net.URL;
  8 import java.net.URLEncoder;
  9 import java.security.KeyManagementException;
 10 import java.security.NoSuchAlgorithmException;
 11 import java.security.SecureRandom;
 12 import java.security.cert.CertificateException;
 13 import java.security.cert.X509Certificate;
 14 import java.util.HashMap;
 15 import java.util.Iterator;
 16 import java.util.Map;
 17 import javax.net.ssl.HostnameVerifier;
 18 import javax.net.ssl.HttpsURLConnection;
 19 import javax.net.ssl.SSLContext;
 20 import javax.net.ssl.SSLSession;
 21 import javax.net.ssl.TrustManager;
 22 import javax.net.ssl.X509TrustManager;
 23 
 24 /**
 25  * Xiwi
 26  * HttpURLConnection类 封装
 27  * 
 28  */
 29 public class HttpUtils {
 30     private URL httpUrl = null;
 31     private HttpURLConnection httpConn = null;
 32 
 33     private Map<String, String> httpHeaders = null;
 34     private String httpCookie = null;
 35     private String httpResult = null;
 36 
 37     // 类的初始化 设置对HTTPS请求的支持
 38     public HttpUtils ( ) throws NoSuchAlgorithmException, KeyManagementException {
 39         SSLContext sslcontext = SSLContext.getInstance("SSL");
 40         TrustManager[] tm = {new MyX509TrustManager()};
 41         sslcontext.init(null, tm, new SecureRandom());
 42         HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
 43             public boolean verify ( String s, SSLSession sslsession ) {
 44                 System.out.println("WARNING: Hostname is not matched for cert.");
 45                 return true;
 46             }
 47         };
 48         HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
 49         HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory());
 50     }
 51 
 52 
 53     public Map<String, String> getHeaders ( ) { return httpHeaders; }
 54     public void setHeader ( Map<String, String> header ) {
 55         if ( httpHeaders == null ) httpHeaders = new HashMap<String, String>();
 56         Iterator<String> iterHeaders = header.keySet().iterator();
 57         while ( iterHeaders.hasNext() ) {
 58             String key = iterHeaders.next();
 59             String value = header.get(key);
 60             httpHeaders.put(key, value);
 61         }
 62     }
 63 
 64     public String getCookie ( ) { return httpCookie; }
 65     public void setCookie ( String cookie ) {
 66         Map<String, String> map = new HashMap<String, String>();
 67         map.put("Cookie", cookie);
 68         setHeader(map);
 69     }
 70 
 71 
 72     // GET 请求
 73     public String sendGet ( String url ) throws IOException {
 74 
 75         httpUrl = new URL(url);
 76         httpConn = (HttpURLConnection)httpUrl.openConnection();
 77 
 78         send("GET", null);
 79 
 80         System.out.println("get ok");
 81         return httpResult;
 82     }
 83 
 84     // POST 请求
 85     public String sendPost ( String url, Map<String, String> params ) throws IOException {
 86 
 87         httpUrl = new URL(url);
 88         httpConn = (HttpURLConnection)httpUrl.openConnection();
 89 
 90         send("POST", params);
 91 
 92         System.out.println("post ok");
 93         return httpResult;
 94     }
 95 
 96 
 97     private void send ( String method, Map<String, String> params ) throws IOException {
 98 
 99         httpConn.setRequestMethod(method);
100 
101         httpConn.setDoInput(true);
102         httpConn.setDoOutput(true);
103         httpConn.setConnectTimeout(5000);
104 
105         // 判断 是否有设置 请求头
106         if ( httpHeaders != null ) {
107             Iterator<String> iter = httpHeaders.keySet().iterator();
108             while ( iter.hasNext() ) {
109                 String key = iter.next();
110                 System.out.print("key: " + key);
111                 System.out.print("\t");
112                 System.out.println("value: " + httpHeaders.get(key));
113                 httpConn.setRequestProperty(key, httpHeaders.get(key));
114             }
115         }
116 
117         // 判断 是否有设置请求数据
118         if ( params != null ) {
119             StringBuffer data = new StringBuffer();
120             Iterator<String> iter = params.keySet().iterator();
121             while ( iter.hasNext() ) {
122                 String key = iter.next();
123                 String value = params.get(key);
124                 data.append(URLEncoder.encode(key, "UTF-8"));
125                 data.append("=").append(
126                 URLEncoder.encode(value, "UTF-8"));
127                 data.append("&");
128             }
129 
130             OutputStreamWriter writer = new OutputStreamWriter(httpConn.getOutputStream());
131             writer.write(data.substring(0, data.length() - 1));
132             writer.flush();
133             writer.close();
134 
135             /* 提交数据方式 第二种
136              PrintWriter printWriter = new PrintWriter(httpConn.getOutputStream());
137              printWriter.write(data.substring(0, data.length() - 1));
138              printWriter.flush();
139              printWriter.close();
140              */
141             /* 提交数据方式 第三种
142              DataOutputStream dos=new DataOutputStream(httpConn.getOutputStream());
143              dos.writeBytes(data.substring(0, data.length() - 1));
144              dos.flush();
145              dos.close();
146              */
147             /* 提交数据方式 第四种
148              OutputStream outwritestream = httpConn.getOutputStream();
149              outwritestream.write(data.substring(0, data.length() - 1).getBytes());
150              outwritestream.flush();
151              outwritestrean.close();
152              */
153             System.out.println("data: " + data.substring(0, data.length() - 1));
154         }
155 
156 
157         //System.out.println("返回代码: " + httpConn.getResponseCode());
158         if ( httpConn.getResponseCode() == 200 ) {
159 
160             // 保存 Cookie
161             httpCookie = httpConn.getHeaderField("Set-Cookie");
162             if ( httpCookie == null || httpCookie.equals("") ) {
163                 httpCookie = httpConn.getHeaderField("Cookie");
164             }
165 
166             // 保存 网页请求头,跳过第一个 HTTP/1.1
167             Map<String, String> mapHeaders = new HashMap<String, String>();
168             Iterator<String> iterHeader = httpConn.getHeaderFields().keySet().iterator();
169             int i = 1;
170             while ( iterHeader.hasNext() ) {
171                 String key = iterHeader.next();
172                 if ( i == 1 ) {continue;}
173                 mapHeaders.put(key, httpConn.getHeaderField(key));
174                 i++;
175             }
176             setHeader(mapHeaders);
177 
178             // 获取网页返回值
179             BufferedReader bf = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
180             String line = "";
181             httpResult = "";
182             while ( (line = bf.readLine()) != null ) {
183                 httpResult += line + "\n";
184             }
185             bf.close();
186         }
187         else {
188             // 请求失败 则 返回网页请求代码
189             httpResult = httpConn.getResponseCode() + "";
190         }
191 
192         httpConn.disconnect();
193     }
194 
195 
196 
197     public String test ( String msg ) {
198         return msg;
199     }
200 
201 
202 
203 
204 }
205 class MyX509TrustManager implements X509TrustManager{
206 
207     @Override
208     public void checkClientTrusted ( X509Certificate[] chain, String authType ) throws CertificateException {
209         // TODO Auto-generated method stub
210 
211     }
212 
213     @Override
214     public void checkServerTrusted ( X509Certificate[] chain, String authType ) throws CertificateException {
215         // TODO Auto-generated method stub
216 
217     }
218 
219     @Override
220     public X509Certificate[] getAcceptedIssuers ( ) {
221         // TODO Auto-generated method stub
222         return null;
223     }
224 }

 

posted @ 2018-12-30 17:24  Xiwi  阅读(1210)  评论(0)    收藏  举报