HttpClient使用


1:单线程请求

请求方法如下

public String postXml(String url, String apiKeyAddr, String apiKey,String xml) throws Exception{
		String responseString = "";
		CloseableHttpClient httpclient = null;
		KeyStore keyStore  = KeyStore.getInstance("PKCS12");
		FileInputStream instream = new FileInputStream(apiKeyAddr);
		String key = apiKey;
		try {
			keyStore.load(instream, key.toCharArray());
		} finally {
			instream.close();
		}
		try {
			SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, key.toCharArray()).build();
			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,new String[] { "TLSv1" },null,SSLConnectionSocketFactory.getDefaultHostnameVerifier());
			httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(httpclient==null){
			httpclient = HttpClients.createDefault();
		}
		
		try {
			HttpPost httpPost = new HttpPost(url);
			StringEntity params = new StringEntity(xml, "UTF-8");
			httpPost.addHeader("Content-Type", "text/xml");
			httpPost.setEntity(params);
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(30000).build();//设置请求和传输超时时间
			httpPost.setConfig(requestConfig);
			System.out.println("executing request:" + httpPost.getRequestLine()); 
			System.out.println("executing request:" + EntityUtils.toString(httpPost.getEntity())); 
			CloseableHttpResponse response = httpclient.execute(httpPost);
			if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
				HttpEntity entity = response.getEntity();
				try {
					if(entity!=null){
						responseString =  EntityUtils.toString(entity,"UTF-8");
						System.out.println(responseString); 
						EntityUtils.consume(entity);  
					}
				} finally{
					response.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(httpclient!=null){
				try {  
					httpclient.close();  
				} catch (IOException e) {  
					e.printStackTrace();  
				}  
			}
		}
		return responseString;
	}

在实际处理过程中,单个请求是OK的,

2:多线程请求


    private static CloseableHttpClient httpClient = null;
    
    static {
        httpClient = getInstance().getHttpClient();
    }
    
    private PoolingHttpClientConnectionManager getHttpClientConnectionManager(){
        try {
//            SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null,  
//                    new TrustSelfSignedStrategy())  
//                    .build();  
//            HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;  
//            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(  
//                    sslcontext,hostnameVerifier);  
            
//            KeyStore keyStore  = KeyStore.getInstance("PKCS12");
//            FileInputStream instream = new FileInputStream(apiKeyAddr);
//            String key = apiKey;
//            try {
//                keyStore.load(instream, key.toCharArray());
//            } finally {
//                instream.close();
//            }
//            try {
//                SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, key.toCharArray()).build();
//                SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,new String[] { "TLSv1" },null,SSLConnectionSocketFactory.getDefaultHostnameVerifier());
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
            
            ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
            LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory.getSocketFactory();
            
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()  
                    .register("http", plainsf)  
                    .register("https", sslsf)  
                    .build();  
            PoolingHttpClientConnectionManager poolConnManager = 
                    new PoolingHttpClientConnectionManager(socketFactoryRegistry);  
            // Increase max total connection to 200  
            poolConnManager.setMaxTotal(200);  
            // Increase default max connection per route to 20  
            poolConnManager.setDefaultMaxPerRoute(20);  
            SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(1000).build();  
            poolConnManager.setDefaultSocketConfig(socketConfig);  
            
            return poolConnManager;
        } catch (Exception e) {  
            e.printStackTrace();
        }  
        return null;
    }
    
    private CloseableHttpClient getHttpClient() {  
        PoolingHttpClientConnectionManager poolConnManager = getHttpClientConnectionManager();
        
        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(1000)  
                .setConnectTimeout(1000).setSocketTimeout(1000).build();  
        CloseableHttpClient httpClient = HttpClients.custom()  
                .setConnectionManager(poolConnManager).setDefaultRequestConfig(requestConfig).build(); 
        /**
         * PoolStats
         * 
         * leased :the number of persistent connections tracked by the connection manager currently being used to execute requests.  
         * available :the number idle persistent connections. 
         * pending : the number of connection requests being blocked awaiting a free connection.  
         * max: the maximum number of allowed persistent connections. 
         */
        if(poolConnManager!=null&&poolConnManager.getTotalStats()!=null) {  
            System.out.println("now client pool "+poolConnManager.getTotalStats().toString());  
        }
        return httpClient;  
    }
    
    private HttpClientUtil(){
    }
    
    public static HttpClientUtil getInstance(){
        return new HttpClientUtil();
    }
    
    
    public static String postXml(String url, String param) {
        String returnStr = null;  
        CloseableHttpResponse response = null;
        HttpPost httpPost = new HttpPost(url);  
        try {  
            long currentTime=System.currentTimeMillis();  
            StringEntity params = new StringEntity(param, "UTF-8");
            httpPost.addHeader("Content-Type", "text/xml");
            httpPost.setEntity(params);
            System.out.println(currentTime+" 开始发送 请求:url"+url);
            
            response = httpClient.execute(httpPost);  
            int status = response.getStatusLine().getStatusCode();  
            HttpEntity entity = response.getEntity();  
            if (status >= 200 && status < 300) {  
                String resopnse = "";
                if(entity != null) {
                    resopnse = EntityUtils.toString(entity,"utf-8");  
                }
                System.out.println(currentTime+" 接收响应:url"+url+" status="+status);
                EntityUtils.consume(entity); 
                return entity != null ? resopnse : null;  
            } else {  
                System.out.println(currentTime+" 接收响应:url"+url+" status="+status+" resopnse="+EntityUtils.toString(entity,"utf-8"));  
                EntityUtils.consume(entity);
                throw new ClientProtocolException("Unexpected response status: " + status);  
            }  
        } catch (Exception e) {  
            e.printStackTrace();
        } finally {  
            try {
                if(response != null){
                    response.close();
                }
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            httpPost.reset();  
        }   
        return returnStr;  
    } 

这里用到了httpclient的连接池,实测500并发无忧


要点,

1.httpclient公用,所有请求交由连接池管理

2.请求配置超时时间,以便在请求处理完成之后连接池自动回收请求资源(此处为回收或重用,有待实测)






HttpClient 是一个开源的 HTTP 客户端库,用于发送 HTTP 请求和接收 HTTP 响应。它提供了简化的 API,使得进行 HTTP 通信变得更加容易。 要使用 HttpClient,首先需要在项目中引入 HttpClient 的依赖。具体的操作方式取决于你使用的开发环境和构建工具。一般来说,如果是使用 Maven 进行项目管理,可以在 pom.xml 文件中添加以下依赖: ```xml <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency> ``` 如果是使用 Gradle 进行项目管理,可以在 build.gradle 文件中添加以下依赖: ```groovy implementation 'org.apache.httpcomponents:httpclient:4.5.13' ``` 接下来就可以在代码中使用 HttpClient 来发送 HTTP 请求了。下面是一个简单的示例: ```java import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; public class HttpClientExample { public static void main(String[] args) throws Exception { HttpClient httpClient = HttpClientBuilder.create().build(); HttpGet request = new HttpGet("http://example.com"); HttpResponse response = httpClient.execute(request); System.out.println("Response Code: " + response.getStatusLine().getStatusCode()); } } ``` 上述示例中,我们创建了一个 HttpClient 实例,并使用该实例发送了一个 GET 请求到 "http://example.com"。获取到的响应存储在 HttpResponse 对象中,我们可以通过调用 `getStatusCode()` 方法获取响应的状态码。 当然,HttpClient 还提供了丰富的 API,可以进行更加复杂的 HTTP 请求和处理。你可以参考 HttpClient 的官方文档来了解更多详细的使用方法和示例。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值