我是靠谱客的博主 知性发卡,最近开发中收集的这篇文章主要介绍整理HttpClient4.5的Fluent API的用法,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

这是接着上一篇对HttpClient4.5的使用总结,HttpClient真是一个好东西,一直保持更新,还推出流畅的写法,使得代码更加简洁易懂,非常好用。

HttpClient Tutorial:

https://hc.apache.org/httpcomponents-client-4.5.x/tutorial/html/index.html

这篇blog介绍的是Fluent API的用法,我把最常用的的get和post方法封装成服务类,如下介绍。

mavne依赖:

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient-osgi</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>

服务类HttpFluentService,封装get和post方法:

import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.Args;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;
/**
* @author wzx
* @time 2017/1/20
*/
public class HttpFluentService {
private static final Logger LOGGER = LoggerFactory.getLogger(HttpFluentService.class);
public String doGet(String url) {
try {
return Request.Get(url).execute().returnContent().asString(Consts.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public String doGet(String url, Map<String, String> paramMap) {
return doGet(url, null, null, null, paramMap);
}
public String doGet(String url, String hostName, Integer port, String schemeName, Map<String, String> paramMap) {
return executeGet(url, hostName, port, schemeName, paramMap);
}
private String executeGet(String url, String hostName, Integer port, String schemeName, Map<String, String> paramMap) {
Args.notNull(url, "url");
url = buildGetParam(url, paramMap);
Request request = Request.Get(url);
request = buildProxy(request, hostName, port, schemeName);
try {
return request.execute().returnContent().asString(Consts.UTF_8);
} catch (IOException e) {
LOGGER.error(e.getMessage(), e.toString());
}
return null;
}
private String buildGetParam(String url, Map<String, String> paramMap) {
Args.notNull(url, "url");
if(MapUtils.isNotEmpty(paramMap)) {
List<NameValuePair> paramList = Lists.newArrayListWithCapacity(paramMap.size());
for (String key : paramMap.keySet()) {
paramList.add(new BasicNameValuePair(key, paramMap.get(key)));
}
//拼接参数
url += "?" + URLEncodedUtils.format(paramList, Consts.UTF_8);
}
return url;
}
public String doPost(String url) {
return doPost(url, null);
}
public String doPost(String url, List<NameValuePair> nameValuePairs) {
return doPost(url, null, null, null, nameValuePairs, null);
}
public void doPost(String url, List<NameValuePair> nameValuePairs, List<File> files) {
doPost(url, null, null, null, nameValuePairs, files);
}
public String doPost(String url, String hostName, Integer port, String schemeName, List<NameValuePair> nameValuePairs, List<File> files) {
return executePost(url, hostName, port, schemeName, nameValuePairs, files);
}
private String executePost(String url, String hostName, Integer port, String schemeName, List<NameValuePair> nameValuePairs, List<File> files) {
Args.notNull(url, "url");
HttpEntity entity = buildPostParam(nameValuePairs, files);
Request request = Request.Post(url).body(entity);
request = buildProxy(request, hostName, port, schemeName);
try {
return request.execute().returnContent().asString(Consts.UTF_8);
} catch (IOException e) {
LOGGER.error(e.getMessage(), e.toString());
}
return null;
}
/**
* 构建POST方法请求参数
* @return
*/
private HttpEntity buildPostParam(List<NameValuePair> nameValuePairs, List<File> files) {
if(CollectionUtils.isEmpty(nameValuePairs) && CollectionUtils.isEmpty(files)) {
return null;
}
if(CollectionUtils.isNotEmpty(files)) {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
for (File file : files) {
builder.addBinaryBody(file.getName(), file, ContentType.APPLICATION_OCTET_STREAM, file.getName());
}
for (NameValuePair nameValuePair : nameValuePairs) {
//设置ContentType为UTF-8,默认为text/plain; charset=ISO-8859-1,传递中文参数会乱码
builder.addTextBody(nameValuePair.getName(), nameValuePair.getValue(), ContentType.create("text/plain", Consts.UTF_8));
}
return builder.build();
} else {
try {
return new UrlEncodedFormEntity(nameValuePairs);
} catch (UnsupportedEncodingException e) {
LOGGER.error(e.getMessage(), e.toString());
}
}
return null;
}
/**
* 设置代理
* @param request
* @param hostName
* @param port
* @param schemeName
* @return
*/
private Request buildProxy(Request request, String hostName, Integer port, String schemeName) {
if(StringUtils.isNotEmpty(hostName) && port != null) {
//设置代理
if (StringUtils.isEmpty(schemeName)) {
schemeName = HttpHost.DEFAULT_SCHEME_NAME;
}
request.viaProxy(new HttpHost(hostName, port, schemeName));
}
return request;
}
}

单元测试:

private String url = "https://hc.apache.org/httpcomponents-client-4.5.x/examples.html";
@Test
public void testGet() {
String result = fluentService.doGet(url);
LOGGER.info("返回结果:{}", result);
}
@Test
public void testGetParam() {
HashMap<String, String> map = Maps.newHashMap();
map.put("name", "wang");
map.put("value", "hello");
String result = fluentService.doGet(url, map);
LOGGER.info("返回结果:{}", result);
}
@Test
public void testGetProxy() {
HashMap<String, String> map = Maps.newHashMap();
map.put("name", "wang");
map.put("value", "hello");
String result = fluentService.doGet(url, "localhost", 8888, null, map);
LOGGER.info("返回结果:{}", result);
}
@Test
public void testPost() {
String result = fluentService.doPost(url, null);
LOGGER.info("返回结果:{}", result);
}
@Test
public void testPostProxy() {
String result = fluentService.doPost(url, "119.28.99.246", 8998, null, null, null);
LOGGER.info("返回结果:{}", result);
}
@Test
public void testPostParam() throws IOException, URISyntaxException {
List<NameValuePair> nameValuePairs = Lists.newArrayList();
nameValuePairs.add(new BasicNameValuePair("name", "王志雄"));
List<File> fileList = Lists.newArrayList();
fileList.add(new File("D:\response.html"));
String result = fluentService.doPost(url, "localhost", 8888, HttpHost.DEFAULT_SCHEME_NAME, nameValuePairs, fileList);
LOGGER.info("返回结果:{}", result);
}

最后

以上就是知性发卡为你收集整理的整理HttpClient4.5的Fluent API的用法的全部内容,希望文章能够帮你解决整理HttpClient4.5的Fluent API的用法所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(33)

评论列表共有 0 条评论

立即
投稿
返回
顶部