首页 > 代码库 > httpclient调用https webservice(rest) 忽略证书

httpclient调用https webservice(rest) 忽略证书

    最近做一个项目需要调用rest风格的webservice,但对方提供一个https的url,所以需要忽略证书去访问。httpclient4.3的api相比3.x改动挺大的,所以,把自己实现的分享出来。代码有些乱,大家参考下。有些方法没贴出来。

 

  1.  这个地方需要重生isTrusted方法,达到忽略本地证书的目的。


     private  SSLConnectionSocketFactory buildSSLContext()
             throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {
         SSLContext sslcontext = SSLContexts.custom().setSecureRandom(new SecureRandom()).loadTrustMaterial(null, new TrustStrategy() {
                     public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                         return true;
                     }
                 }).build();
         SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] {"TLSv1"}, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
         return sslsf;
     }

2. 这部分是具体调用webservice,功能是实现上传一个文件。

 CloseableHttpClient httpclient = null;
  HttpPost httppost = null;
  try {
   // create upload file
   uploadFile = createUploaFile(user, appCenterUrl, buildTypeId);
   //  get upload url
   String uploadUrl = getUploadUrl(userMqa, mqaUrl);
   // get httpclient
   SSLConnectionSocketFactory sslsf = buildSSLContext();
   httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
   httppost = new HttpPost(uploadUrl);
   httppost.addHeader(HttpHeaders.AUTHORIZATION, gererateEncoudAuth(userMqa));
   FileBody bin = new FileBody(uploadFile);
   StringBody comment = new StringBody("A binary file of some kind", ContentType.MULTIPART_FORM_DATA);
   HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("resource", bin).addPart("comment", comment).build();
   httppost.setEntity(reqEntity);
   System.out.println("executing request " + httppost.getRequestLine());
   
   CloseableHttpResponse httpResponse = httpclient.execute(httppost);
   try {
    System.out.println(httpResponse.getStatusLine().getStatusCode());
   
    HttpEntity resEntity = httpResponse.getEntity();
        
    if (resEntity != null) {
     boolean flag = true;
     System.out.println("Response content length: " + resEntity.getContentLength());
     String resultStr = EntityUtils.toString(resEntity);
    }
   } finally {
    if (httpResponse != null) {
     httpResponse.close();
    }
   }
  } catch (Exception e) {
    e.printStackTrace();

  } finally {
   try {
    if (httppost != null) {
     httppost.releaseConnection();
    }
    if (httpclient != null) {
     httpclient.close();
   }
   } catch (IOException e) {
    e.printStackTrace();
   }
  }

 


 

本文出自 “小宇宙” 博客,请务必保留此出处http://microcosm.blog.51cto.com/8612978/1569027

httpclient调用https webservice(rest) 忽略证书