HTTPClient 简单使用

HttpClient 的用模拟http请求的工具,一般用在测试Http的请求,下面是一个简单的例子:

	public void testHttpClient() throws Exception {
		String localUrl = "http://127.0.0.1/XXX.html";
		//创建HttpClientBuilder  
		HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();  
		//HttpClient  
		CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
		HttpPost httpPost = new HttpPost(localUrl);  
		List<NameValuePair> vals = new ArrayList<NameValuePair>();
		// 添加参数
		vals.add(new BasicNameValuePair("Name","bobobo"));
		httpPost.setEntity(new UrlEncodedFormEntity(vals,HTTP.UTF_8));   
		HttpResponse response = closeableHttpClient.execute(httpPost);
		if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
			HttpEntity entity = response.getEntity();  
			System.out.println("status:" + response.getStatusLine());  
			System.out.println("contentEncoding:" + entity.getContentEncoding());  
			System.out.println("response content:" + EntityUtils.toString(entity));
		}
	}

 补充一个更详细实例:

    protected String httpPostWithJSON(String url, String json) {  
        String  body = StringUtils.EMPTY;
        
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();    
        int timeout = 15 * 1000;
        RequestConfig.Builder requestBuilder = RequestConfig.custom()
                .setConnectTimeout(timeout)
                .setConnectionRequestTimeout(timeout)
                .setSocketTimeout(timeout);
        httpClientBuilder.setDefaultRequestConfig(requestBuilder.build());
        CloseableHttpClient closeableHttpClient = httpClientBuilder.build();  
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
        try {
            StringEntity se = new StringEntity(json,Consts.UTF_8);
            httpPost.setEntity(se); 
            
            HttpResponse response = closeableHttpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();  
            
            if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){  
                body = EntityUtils.toString(entity,Consts.UTF_8);  
            }
        } catch (UnsupportedEncodingException e) {
            logger.error("httpPostWithJSON UnsupportedEncodingException error : ", e);
        } catch (ClientProtocolException e) {
            logger.error("httpPostWithJSON ClientProtocolException error : ", e);
        } catch (IOException e) {
            logger.error("httpPostWithJSON IOException error : ", e);
        } 
        return body;
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值