1. 程式人生 > >Java訪問https介面實現(JDK/Httpclient4)

Java訪問https介面實現(JDK/Httpclient4)

用兩種方式分別實現了,第一種是jdk原生的,程式碼稍微多點,第二種是基於httpclient4版本的。在我的機器上,訪問同一個介面原生的效能要好很多(前者900ms,後者5.7s左右),httpclient主要效能消耗在"HttpResponse res = client.execute(post);",大約佔總執行時間的90%。

1、JDK API

Java程式碼  收藏程式碼
  1. private static final String METHOD_POST = "POST";  
  2.     private static final String DEFAULT_CHARSET = "utf-8";  
  3.     public static String doPost(String url, String params, String charset, int connectTimeout, int readTimeout) throws Exception {  
  4.         String ctype = "application/json;charset="
     + charset;  
  5.         byte[] content = {};  
  6.         if(params != null){  
  7.             content = params.getBytes(charset);  
  8.         }  
  9.         return doPost(url, ctype, content, connectTimeout, readTimeout);  
  10.     }  
  11.     public static String doPost(String url, String ctype, byte[] content,int connectTimeout,int
     readTimeout) throws Exception {  
  12.         HttpsURLConnection conn = null;  
  13.         OutputStream out = null;  
  14.         String rsp = null;  
  15.         try {  
  16.             try{  
  17.                 SSLContext ctx = SSLContext.getInstance("TLS");  
  18.                 ctx.init(new KeyManager[0], new TrustManager[] {new
     DefaultTrustManager()}, new SecureRandom());  
  19.                 SSLContext.setDefault(ctx);  
  20.                 conn = getConnection(new URL(url), METHOD_POST, ctype);   
  21.                 conn.setHostnameVerifier(new HostnameVerifier() {  
  22.                     @Override  
  23.                     public boolean verify(String hostname, SSLSession session) {  
  24.                         return true;  
  25.                     }  
  26.                 });  
  27.                 conn.setConnectTimeout(connectTimeout);  
  28.                 conn.setReadTimeout(readTimeout);  
  29.             }catch(Exception e){  
  30.                 log.error("GET_CONNECTOIN_ERROR, URL = " + url, e);  
  31.                 throw e;  
  32.             }  
  33.             try{  
  34.                 out = conn.getOutputStream();  
  35.                 out.write(content);  
  36.                 rsp = getResponseAsString(conn);  
  37.             }catch(IOException e){  
  38.                 log.error("REQUEST_RESPONSE_ERROR, URL = " + url, e);  
  39.                 throw e;  
  40.             }  
  41.         }finally {  
  42.             if (out != null) {  
  43.                 out.close();  
  44.             }  
  45.             if (conn != null) {  
  46.                 conn.disconnect();  
  47.             }  
  48.         }  
  49.         return rsp;  
  50.     }  
  51.     private static class DefaultTrustManager implements X509TrustManager {  
  52.         @Override  
  53.         public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}  
  54.         @Override  
  55.         public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}  
  56.         @Override  
  57.         public X509Certificate[] getAcceptedIssuers() {  
  58.             return null;  
  59.         }  
  60.     }  
  61.     private static HttpsURLConnection getConnection(URL url, String method, String ctype)  
  62.             throws IOException {  
  63.         HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();  
  64.         conn.setRequestMethod(method);  
  65.         conn.setDoInput(true);  
  66.         conn.setDoOutput(true);  
  67.         conn.setRequestProperty("Accept""text/xml,text/javascript,text/html");  
  68.         conn.setRequestProperty("User-Agent""stargate");  
  69.         conn.setRequestProperty("Content-Type", ctype);  
  70.         return conn;  
  71.     }  
  72.     protected static String getResponseAsString(HttpURLConnection conn) throws IOException {  
  73.         String charset = getResponseCharset(conn.getContentType());  
  74.         InputStream es = conn.getErrorStream();  
  75.         if (es == null) {  
  76.             return getStreamAsString(conn.getInputStream(), charset);  
  77.         } else {  
  78.             String msg = getStreamAsString(es, charset);  
  79.             if (StringUtils.isEmpty(msg)) {  
  80.                 throw new IOException(conn.getResponseCode() + ":" + conn.getResponseMessage());  
  81.             } else {  
  82.                 throw new IOException(msg);  
  83.             }  
  84.         }  
  85.     }  
  86.     private static String getStreamAsString(InputStream stream, String charset) throws IOException {  
  87.         try {  
  88.             BufferedReader reader = new BufferedReader(new InputStreamReader(stream, charset));  
  89.             StringWriter writer = new StringWriter();  
  90.             char[] chars = new char[256];  
  91.             int count = 0;  
  92.             while ((count = reader.read(chars)) > 0) {  
  93.                 writer.write(chars, 0, count);  
  94.             }  
  95.             return writer.toString();  
  96.         } finally {  
  97.             if (stream != null) {  
  98.                 stream.close();  
  99.             }  
  100.         }  
  101.     }  
  102.     private static String getResponseCharset(String ctype) {  
  103.         String charset = DEFAULT_CHARSET;  
  104.         if (!StringUtils.isEmpty(ctype)) {  
  105.             String[] params = ctype.split(";");  
  106.             for (String param : params) {  
  107.                 param = param.trim();  
  108.                 if (param.startsWith("charset")) {  
  109.                     String[] pair = param.split("="2);  
  110.                     if (pair.length == 2) {  
  111.                         if (!StringUtils.isEmpty(pair[1])) {  
  112.                             charset = pair[1].trim();  
  113.                         }  
  114.                     }  
  115.                     break;  
  116.                 }  
  117.             }  
  118.         }  
  119.         return charset;  
  120.     }  
 

2、Httpclient API 

Java程式碼  收藏程式碼
  1. public static JSONObject post(String url, String json) {  
  2.         HttpClient client = new DefaultHttpClient();  
  3.         client = WebClientDevWrapper.wrapClient(client);  
  4.         HttpPost post = new HttpPost(url);  
  5.         JSONObject response = null;  
  6.         try {  
  7.             StringEntity s = new StringEntity(json);  
  8.             s.setContentEncoding("UTF-8");  
  9.             s.setContentType("application/json");  
  10.             post.setEntity(s);  
  11.             Long startTime = System.currentTimeMillis();  
  12.             HttpResponse res = client.execute(post);  
  13.             System.out.println(System.currentTimeMillis() - startTime);  
  14.             if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {  
  15.                 HttpEntity entity = res.getEntity();  
  16.                 String charset = EntityUtils.getContentCharSet(entity);  
  17.                 if(charset == null){  
  18.                     charset = "utf-8";  
  19.                 }  
  20.                 response = new JSONObject(new JSONTokener(  
  21.                         new InputStreamReader(entity.getContent(), charset)));  
  22.             }  
  23.         } catch (Exception e) {  
  24.             throw new RuntimeException(e);  
  25.         }  
  26.         return response;  
  27.     }  
  28.     public static class WebClientDevWrapper {  
  29.         public static HttpClient wrapClient(HttpClient base) {  
  30.             try {  
  31.                 SSLContext ctx = SSLContext.getInstance("TLS");  
  32.                 X509TrustManager tm = new X509TrustManager() {  
  33.                     @Override  
  34.                     public X509Certificate[] getAcceptedIssuers() {  
  35.                         return null;  
  36.                     }  
  37.                     @Override  
  38.                     public void checkClientTrusted(  
  39.                             java.security.cert.X509Certificate[] chain,  
  40.                             String authType)  
  41.                             throws java.security.cert.CertificateException {  
  42.                     }  
  43.                     @Override  
  44.                     public void checkServerTrusted(  
  45.                             java.security.cert.X509Certificate[] chain,  
  46.                             String authType)  
  47.                             throws java.security.cert.CertificateException {  
  48.                     }  
  49.                 };  
  50.                 ctx.init(nullnew TrustManager[] { tm }, null);  
  51.                 SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);  
  52.                 ClientConnectionManager ccm = base.getConnectionManager();  
  53.                 SchemeRegistry sr = ccm.getSchemeRegistry();  
  54.                 sr.register(new Scheme("https"443, ssf));  
  55.                 return new DefaultHttpClient(ccm, base.getParams());  
  56.             } catch (Exception ex) {  
  57.                 ex.printStackTrace();  
  58.                 return null;  
  59.             }  
  60.         }  
  61.     }