HttpClient 不同版本 不同用法
阿新 • • 發佈:2019-01-28
httpClient 4.32 帶認證的用法
public static String httpPost(String url) throws Exception{ String host = WebRTCPropertyManager.getValue("HOST"); String user = WebRTCPropertyManager.getValue("USER"); String password = WebRTCPropertyManager.getValue("PASSWORD"); url="https://"+host+url; CloseableHttpClient httpClient = null; ConnectionConfig connConfig = ConnectionConfig.custom().setCharset(Charset.forName("utf-8")).build(); KeyStore trustStore = null; SSLContext sslContext = null; trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); sslContext = SSLContexts.custom().useTLS().loadTrustMaterial(trustStore, new AnyTrustStrategy()).build(); SSLConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(sslContext,SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST,AuthScope.ANY_PORT, AuthScope.ANY_SCHEME, AuthPolicy.BASIC),new UsernamePasswordCredentials(user, password)); HttpClientBuilder hcb = HttpClientBuilder.create(); hcb.setDefaultCredentialsProvider(credsProvider); httpClient = HttpClients.custom().setDefaultConnectionConfig(connConfig).setDefaultCredentialsProvider(credsProvider).setSSLSocketFactory(sslSF).build(); HttpGet httpGet = new HttpGet(url); CloseableHttpResponse httpresponse = httpClient.execute(httpGet); String result = EntityUtils.toString(httpresponse.getEntity(), "UTF-8"); return result; }
httpClient 4.3.1 普通寫法
public static String httpPost(String url,String xml,String type){ String result=""; String dataType="text/xml"; if(type.equalsIgnoreCase("json")){ dataType="application/json"; } HttpClient client= new HttpClient(); PostMethod post= new PostMethod(url); RequestEntity re; try { re = new StringRequestEntity(xml, dataType, "UTF-8"); post.setRequestEntity(re); client.executeMethod(post); result=post.getResponseBodyAsString(); } catch (Exception e) { e.printStackTrace(); } return result; }