IT序号网

HttpClient 不同版本 不同用法

flyfish 2021年06月13日 编程语言 292 0


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; 
		 
	}



 下载地址 




评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!