Java访问https接口实现

        用两种方式分别实现了,第一种是jdk原生的,代码稍微多点,第二种是基于httpclient4版本的。在我的机器上,访问同一个接口原生的性能要好很多(前者900ms,后者5.7s左右),httpclient主要性能消耗在"HttpResponse res = client.execute(post);",大约占总执行时间的90%。

 

 

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

 

Java代码  Java访问https接口实现
  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.   
  12.             Long startTime = System.currentTimeMillis();  
  13.             HttpResponse res = client.execute(post);  
  14.             System.out.println(System.currentTimeMillis() - startTime);  
  15.             if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {  
  16.                 HttpEntity entity = res.getEntity();  
  17.                 String charset = EntityUtils.getContentCharSet(entity);  
  18.                 if(charset == null){  
  19.                     charset = "utf-8";  
  20.                 }  
  21.                 response = new JSONObject(new JSONTokener(  
  22.                         new InputStreamReader(entity.getContent(), charset)));  
  23.             }  
  24.         } catch (Exception e) {  
  25.             throw new RuntimeException(e);  
  26.         }  
  27.         return response;  
  28.     }  
  29.   
  30.     public static class WebClientDevWrapper {  
  31.         public static HttpClient wrapClient(HttpClient base) {  
  32.             try {  
  33.                 SSLContext ctx = SSLContext.getInstance("TLS");  
  34.                 X509TrustManager tm = new X509TrustManager() {  
  35.                     @Override  
  36.                     public X509Certificate[] getAcceptedIssuers() {  
  37.                         return null;  
  38.                     }  
  39.   
  40.                     @Override  
  41.                     public void checkClientTrusted(  
  42.                             java.security.cert.X509Certificate[] chain,  
  43.                             String authType)  
  44.                             throws java.security.cert.CertificateException {  
  45.                           
  46.                     }  
  47.   
  48.                     @Override  
  49.                     public void checkServerTrusted(  
  50.                             java.security.cert.X509Certificate[] chain,  
  51.                             String authType)  
  52.                             throws java.security.cert.CertificateException {  
  53.                           
  54.                     }  
  55.                 };  
  56.                 ctx.init(null, new TrustManager[] { tm }, null);  
  57.                 SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);  
  58.                 ClientConnectionManager ccm = base.getConnectionManager();  
  59.                 SchemeRegistry sr = ccm.getSchemeRegistry();  
  60.                 sr.register(new Scheme("https", 443, ssf));  
  61.                 return new DefaultHttpClient(ccm, base.getParams());  
  62.             } catch (Exception ex) {  
  63.                 ex.printStackTrace();  
  64.                 return null;  
  65.             }  
  66.         }  
  67.     }  
 

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

上一篇:Python9-MySQL索引-外键-day43


下一篇:C# 基于Arcface SDK实现人脸识别和注册