HttpClient Fluent API使用方法

Posted by hcy on June 21, 2019

HttpClient Fluent API使用方法

1.加入 maven


 <dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.8</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>fluent-hc</artifactId>
    <version>4.5.8</version>
</dependency>

2.基本用法

1
2
3
4
5
6
7
8
9
10
		Request.Get("http://www.baidu.com")
				.execute()
				.handleResponse(new ResponseHandler<String>() {
					@Override
					public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
						return EntityUtils.toString(response.getEntity(), "utf-8");
					}
				});

3.额外参数

1
2
3
4
5
6
			Request.Get("http://www.baidu.com")
					.connectTimeout(3000)
					.addHeader("key","value")
					.userAgent("test")
					.execute();

4.post

1
2
3
4
5
6
			/*添加一个post参数*/
			BasicNameValuePair pair = new BasicNameValuePair("name","hh");
			Request.Post("http://www.baidu.com")
					.connectTimeout(3000)
					.bodyForm(pair)
					.execute();

5.post json

1
2
3
4
5
		Request.Post("http://www.baidu.com")
					.connectTimeout(3000)
					.bodyString(JSON.toJSONString(var), ContentType.APPLICATION_JSON)
					.execute();

###

1
2
3
4
5
6
			Request.Post("https://www.baidu.com")
					.useExpectContinue()
					.version(HttpVersion.HTTP_1_1)
					.bodyString("啦啦啦", ContentType.DEFAULT_TEXT)
					.execute();


转载请注明出处:https://www.huangchaoyu.com/2019/06/21/HttpClient-Fluent-API使用方法/