首页 > 学院 > 开发设计 > 正文

HttpClient4.3.1

2019-11-08 01:12:14
字体:
来源:转载
供稿:网友
最近因业务需要,用HttpClient4.3.1版本进行业务开发,对HttpClient4.3.1研究了一下,但是网上对于这个版本的信息很少,缺少相关的文档资料,本文总结了HttpClient4.3.1相关用法。

1.创建HttpClient客户端

HttpClientBuilder clientbuilder = HttpClientBuilder.create();CloseableHttpClient httpclient = clientbuilder.build();

2.发送Get请求

String url = "http://www.baidu.com";HttpGet httpGet = new HttpGet(url);HttPResponse httpResponse = httpclient.execute(httpGet);3.设置超时时间

RequestConfig requestconfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(5000).build();httpGet.setConfig(requestconfig);4.获取响应信息实体、响应状态、响应信息

HttpEntity entity = httpResponse.getEntity();StatusLine status = httpResponse.getStatusLine();if(entity!=null){	String data = EntityUtils.toString(entity);}简单的小例子:

	public static void main(String[] args) throws ClientProtocolException, IOException {				//创建HttpClient客户端		HttpClientBuilder clientbuilder = HttpClientBuilder.create();		CloseableHttpClient httpclient = clientbuilder.build();				String url = "http://www.baidu.com";		HttpGet httpGet = new HttpGet(url);				//设置超时时间		RequestConfig requestconfig = RequestConfig.custom().setConnectTimeout(5000)				.setConnectionRequestTimeout(5000).setSocketTimeout(5000).build();		httpGet.setConfig(requestconfig);				try{			//发送get请求			HttpResponse httpResponse = httpclient.execute(httpGet);						//获取响应消息实体			HttpEntity entity = httpResponse.getEntity();						//获取响应状态			StatusLine status = httpResponse.getStatusLine();						if(entity!=null){				//获取响应信息				String data = EntityUtils.toString(entity);			}		}catch(IOException e){			e.printStackTrace();		}finally{			try{			httpclient.close();			}catch(IOException e){				e.printStackTrace();			}		}	}

HttpClient4.3.1 API文档:http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/overview-summary.htmlHttpClient4.3.1相关jar包:http://pan.baidu.com/s/1qXN4Q6K
上一篇:线程锁Lock

下一篇:Struts2---国际化

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表