整理HttpClient4.5的Fluent API的用法
来源:互联网 发布:朗读语文课文软件 编辑:程序博客网 时间:2024/06/07 00:45
这是接着上一篇对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); }
0 0
- 整理HttpClient4.5的Fluent API的用法
- HttpClient4.2 Fluent API学习
- HttpClient4.2 Fluent API学习
- HttpClient4.2 Fluent API学习
- HttpClient Fluent API 的使用
- Apache HttpClient4.3 Fluent API使用心得小结
- joor,一个基于fluent API设计的反射API
- 使用Data Annotations和Fluent API配置数据库的映射
- HTTPClient4.5.2学习笔记(五):流式请求API(Fluent API)
- httpclient4.5 的一些细节
- httpclient4.5 的一些细节
- FLUENT Solver的选择
- Fluent NHibernate的初学者
- HttpClient4.1入门教程-利用官方例子讲解httpClient4.1的用法
- HttpClient4.1入门教程-利用官方例子讲解httpClient4.1的用法
- Zookeeper实例Curator API-使用Fluent风格的API接口来创建一个ZooKeeper客户端
- httpclient4 发送http请求的get和post用法
- httpclient4.5的get和post方法
- 如何在Windows7 设置node的环境变量NODE_ENV=production
- 文本相似度的设计与实现
- python中常用的base64 md5 aes des crc32等的加密解密
- 奇偶排序
- 设计模式练习(10)——外观模式
- 整理HttpClient4.5的Fluent API的用法
- Ubuntu 16.04 interface and networking service.
- 使用 ss 代理增加 gradle 编译速度
- poj 2253 Frogger
- 自己的年终总结
- Spring+EhCache缓存实例(详细讲解+源码下载)
- 最近安装了Linux,本地使用xshell,但连不上,才发现是防火墙的原因
- 分布式锁实现方式一 基于zookeeper的分布式锁
- MySQL优化技巧