前言

大多数Java应用程序都会通过HTTP协议来调用接口访问各种网络资源,JDK也提供了相应的HTTP工具包,但是使用起来不够方便灵活,所以我们可以利用Apache的HttpClient来封装一个具有访问HTTP协议基本功能的高效工具类,为后续开发使用提供方便。

文章要点:

  • HttpClient使用流程
  • 工具类封装
  • 使用实例

HttpClient使用流程

1、导入Maven依赖

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.11</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>

2、创建HttpClient实例

HttpClient client = HttpClientBuilder.create().build();

3、创建请求方法的实例

GET请求使用HttpGet,POST请求使用HttpPost,并传入请求的URL

// POST请求
HttpPost post = new HttpPost(url);
// GET请求,URL中带请求参数
HttpGet get = new HttpGet(url);

4、添加请求参数

普通形式

List<NameValuePair> list = new ArrayList<>();
list.add(new BasicNameValuePair("username", "admin"));
list.add(new BasicNameValuePair("password", "123456")); // GET请求方式
// 由于GET请求的参数是拼装在URL后方,所以需要构建一个完整的URL,再创建HttpGet实例
URIBuilder uriBuilder = new URIBuilder("http://www.baidu.com");
uriBuilder.setParameters(list);
HttpGet get = new HttpGet(uriBuilder.build()); // POST请求方式
post.setEntity(new UrlEncodedFormEntity(list, Charsets.UTF_8));

JSON形式

Map<String,String> map = new HashMap<>();
map.put("username", "admin");
map.put("password", "123456");
Gson gson = new Gson();
String json = gson.toJson(map, new TypeToken<Map<String, String>>() {}.getType());
post.setEntity(new StringEntity(json, Charsets.UTF_8));
post.addHeader("Content-Type", "application/json");

5、发送请求

调用HttpClient实例的execute方法发送请求,返回一个HttpResponse对象

HttpResponse response = client.execute(post);

6、获取结果

String result = EntityUtils.toString(response.getEntity());

7、释放连接

post.releaseConnection();

工具类封装

HttpClient工具类代码(根据相应使用场景进行封装):

public class HttpClientUtil {
// 发送GET请求
public static String getRequest(String path, List<NameValuePair> parametersBody) throws RestApiException, URISyntaxException {
URIBuilder uriBuilder = new URIBuilder(path);
uriBuilder.setParameters(parametersBody);
HttpGet get = new HttpGet(uriBuilder.build());
HttpClient client = HttpClientBuilder.create().build();
try {
HttpResponse response = client.execute(get);
int code = response.getStatusLine().getStatusCode();
if (code >= 400)
throw new RuntimeException((new StringBuilder()).append("Could not access protected resource. Server returned http code: ").append(code).toString());
return EntityUtils.toString(response.getEntity());
}
catch (ClientProtocolException e) {
throw new RestApiException("postRequest -- Client protocol exception!", e);
}
catch (IOException e) {
throw new RestApiException("postRequest -- IO error!", e);
}
finally {
get.releaseConnection();
}
} // 发送POST请求(普通表单形式)
public static String postForm(String path, List<NameValuePair> parametersBody) throws RestApiException {
HttpEntity entity = new UrlEncodedFormEntity(parametersBody, Charsets.UTF_8);
return postRequest(path, "application/x-www-form-urlencoded", entity);
} // 发送POST请求(JSON形式)
public static String postJSON(String path, String json) throws RestApiException {
StringEntity entity = new StringEntity(json, Charsets.UTF_8);
return postRequest(path, "application/json", entity);
} // 发送POST请求
public static String postRequest(String path, String mediaType, HttpEntity entity) throws RestApiException {
logger.debug("[postRequest] resourceUrl: {}", path);
HttpPost post = new HttpPost(path);
post.addHeader("Content-Type", mediaType);
post.addHeader("Accept", "application/json");
post.setEntity(entity);
try {
HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(post);
int code = response.getStatusLine().getStatusCode();
if (code >= 400)
throw new RestApiException(EntityUtils.toString(response.getEntity()));
return EntityUtils.toString(response.getEntity());
}
catch (ClientProtocolException e) {
throw new RestApiException("postRequest -- Client protocol exception!", e);
}
catch (IOException e) {
throw new RestApiException("postRequest -- IO error!", e);
}
finally {
post.releaseConnection();
}
}
}

使用实例

GET请求

List<NameValuePair> parametersBody = new ArrayList();
parametersBody.add(new BasicNameValuePair("userId", "admin"));
String result = HttpClientUtil.getRequest("http://www.test.com/user",parametersBody);

POST请求

List<NameValuePair> parametersBody = new ArrayList();
parametersBody.add(new BasicNameValuePair("username", "admin"));
parametersBody.add(new BasicNameValuePair("password", "123456"));
String result = HttpClientUtil.postForm("http://www.test.com/login",parametersBody);

POST请求(JSON形式)

Map<String,String> map = new HashMap<>();
map.put("username", "admin");
map.put("password", "123456");
Gson gson = new Gson();
String json = gson.toJson(map, new TypeToken<Map<String, String>>() {}.getType());
String result = HttpClientUtil.postJSON("http://www.test.com/login", json);

关于HttpClient的详细介绍看这里:HttpClient入门

本文为作者kMacro原创,转载请注明来源:https://zkhdev.github.io/2018/10/12/java_dev5/

Java开发小技巧(五):HttpClient工具类的更多相关文章

  1. Java开发小技巧(三):Maven多工程依赖项目

    前言 本篇文章基于Java开发小技巧(二):自定义Maven依赖中创建的父工程project-monitor实现,运用我们自定义的依赖包进行多工程依赖项目的开发. 下面以多可执行Jar包项目的开发为例 ...

  2. Java开发小技巧(六):使用Apache POI读取Excel

    前言 在数据仓库中,ETL最基础的步骤就是从数据源抽取所需的数据,这里所说的数据源并非仅仅是指数据库,还包括excel.csv.xml等各种类型的数据接口文件,而这些文件中的数据不一定是结构化存储的, ...

  3. Java开发小技巧(一)

    前言 相信许多程序员在看别人写的代码的时候,会有怀疑人生的感想,面对一堆天书一样的代码,很难摸清作者的思路,最后选择了重构,如果你认同上面这个作法,说明了两个问题:要么原来的开发者技术菜.要么你技术菜 ...

  4. Java开发小技巧(二):自定义Maven依赖

    前言 我们在项目开发中经常会将一些通用的类.方法等内容进行打包,打造成我们自己的开发工具包,作为各个项目的依赖来使用. 一般的做法是将项目导出成Jar包,然后在其它项目中将其导入,看起来很轻松,但是存 ...

  5. Java开发小技巧(四):配置文件敏感信息处理

    前言 不知道在上一篇文章中你有没有发现,jdbc.properties中的数据库密码配置是这样写的: jdbc.password=5EF28C5A9A0CE86C2D231A526ED5B388 其实 ...

  6. java开发小技巧

    链接地址:http://www.cnblogs.com/zkh101/p/8083368.html 人脸识别地址:http://blog.csdn.net/gitchat/article/detail ...

  7. Windows统一平台: 开发小技巧

    Windows统一平台: 开发小技巧 技巧一: 在手机端拓展你应用的显示区域.(WP8.1中也适用) 对于Windows Phone系统的手机, 手机屏幕最上方为系统状态栏(System Tray), ...

  8. TP开发小技巧

    TP开发小技巧原文地址http://wp.chenyuanzhao.com/wp/2016/07/23/tp%E5%BC%80%E5%8F%91%E5%B0%8F%E6%8A%80%E5%B7%A7/ ...

  9. Android快速开发系列 10个常用工具类

    转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/38965311,本文出自[张鸿洋的博客] 打开大家手上的项目,基本都会有一大批的辅 ...

随机推荐

  1. 代码分析工具推荐Understand

    之前看ogitor ,第一次看到那么多代码~~不知道从哪里下手,而且好多东西都不会Ogre什么的都不是很清楚,对ogitor的代码结构的了解就更不用提了.晕头转向的 不知道从哪里下手,一点点的看起来好 ...

  2. sudo:*:command not found

    原因:执行sudo后,sudo会根据visudo里面配置的secure_path来找寻命令,所以sudo尽量使用绝对路径 sudo bash-c "echo $PATH"也可以看到 ...

  3. July 15th 2017 Week 28th Saturday

    If I can't hear your heartbeat, you are too far away. 如果我听不见你的心跳,那是因为你离我太远了. Only when the two tight ...

  4. 薄弱的交互页面之新浪微博到博客的储存型xss漏洞

    首先分享一片博文到微博,然后 在微博评论xss code 最后回到博客点击举报就触发xss了 点击举报 Xss之2 首先还是分享一片博文到微博,然后评论xsscode 回到我的博客个人中心,查看评论 ...

  5. Alpha Scrum1

    Alpha Scrum1 牛肉面不要牛肉不要面 Alpha项目冲刺(团队作业5) 各个成员在 Alpha 阶段认领的任务 林志松:音乐网页前端页面编写,博客发布 吴沂章:博客编写 林锃寒:前端页面编写 ...

  6. Override和Overload的含义去区别

    java中的继承,方法覆盖(重写)override与方法的重载overload的区别  方法的重写(Overriding)和重载(Overloading)是Java多态性的不同表现.   重写(Ove ...

  7. interaction-oriented architecture - MVC

    MVC(Model-View-Controller),它是专门针 对交互系统提出的,所以如果我们要构建一个交互系统,那么我们就可以直接应用MVC模式,然后 在该模式所搭建的场景的启发下去发现Model ...

  8. jquery Jbox 插件实现弹出窗口在修改的数据之后,关闭弹出窗口刷新父页面的问题

    http://blog.csdn.net/nsdnresponsibility/article/details/51282797 问题如题: 这里我们在父页面定义一个全局的变量来标识是否需要刷新父页面 ...

  9. BZOJ 2120 数颜色 【带修改莫队】

    任意门:https://www.lydsy.com/JudgeOnline/problem.php?id=2120 2120: 数颜色 Time Limit: 6 Sec  Memory Limit: ...

  10. VC++读写*.ini配置文件

    ini文件(即Initialization file),这种类型的文件中通常存放的是一个程序的初始化信息.ini文件由若干个节(Section)组成,每个Section由若干键(Key)组成,每个Ke ...