標籤:httpclient
最近做一個項目需要調用rest風格的webservice,但對方提供一個https的url,所以需要忽略認證去訪問。httpclient4.3的api相比3.x改動挺大的,所以,把自己實現的分享出來。代碼有些亂,大家參考下。有些方法沒貼出來。
-
這個地方需要重生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) 忽略認證