Java开发小技巧(五):HttpClient工具类
前言
大多数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/。
转载于:https://www.cnblogs.com/zkh101/p/9777973.html
Java开发小技巧(五):HttpClient工具类相关推荐
- Java开发小技巧(六):使用Apache POI读取Excel
前言 在数据仓库中,ETL最基础的步骤就是从数据源抽取所需的数据,这里所说的数据源并非仅仅是指数据库,还包括excel.csv.xml等各种类型的数据接口文件,而这些文件中的数据不一定是结构化存储的, ...
- java开发AmazonS3对象存储的工具类
上两节说了文档上默认不用证书的方式操作对象,但大部分时候出于安全考虑是要用到证书认证的.下面就是对这种情况下的对象操作. 1.引入pom.xml <project xmlns="htt ...
- java开发中spring常用的工具类
内置的resouce类型 UrlResource ClassPathResource FileSystemResource ServletContextResource InputStreamReso ...
- 开发小技巧【开发者工具】
一.开发者工具(Developer Tools) Spring Boot 提供了一套额外的工具,可以让我们更加愉快的开发应用. spring-boot-devtools 模块可以包含在任何项目中, ...
- java中将数字颠倒的工具类,java开发中常用的数字工具类
import java.math.BigDecimal; import org.apache.commons.lang.RandomStringUtils; public class NumberUt ...
- java 多项目_Java开发小技巧(三):Maven多工程依赖项目
Maven多工程依赖项目开发流程 前言 本篇文章基于Java开发小技巧(二):自定义Maven依赖中创建的父工程project-monitor实现,运用我们自定义的依赖包进行多工程依赖项目的开发. 下 ...
- apache httpclient 工具类_HttpClient 和Mycat 主从节点和读写分离
第175次(HttpClient) 学习主题:HttpClient 学习目标: 1 掌握HttpClient自定义工具以及HttpClient具体的使用 对应视频: http://www.itbaiz ...
- 提高效率的Java代码优化小技巧
可以提高效率的Java代码优化小技巧 前言 代码优化 ,一个很重要的课题.可能有些人觉得没用,一些细小的地方有什么好修改的,改与不改对于代码的运行效率有什么影响呢?这个问题我是这么考虑的,就像大海里面 ...
- Silverlight 游戏开发小技巧:扇形排列元素
Silverlight 游戏开发小技巧:扇形排列元素 斗地主风靡了大江南北,在春晚都做免费性推广,棋牌游戏平台几乎将其作为标配,但是牌类游戏总是一成不变的样子--横向排列,如果扇形排列应该更加符合真实 ...
最新文章
- 蛰伏7年!他一天发表两篇Nature,还曾是曹原的师弟!
- urlencode使用场景
- c语言全排列算法_一文学会回溯搜索算法解题技巧
- Linux上用Jenkins执行shell
- vfp字符转换数值_JS数据类型转换与字面量
- SharePoint 2007 在Windows Server 2008上列表Open with Windows Explorer失效 解决
- 《统一沟通-微软-实战》-7-配置-2-呼叫寄存
- 1.安装编译软件(keil)
- 发力大数据营销 神马搜索获年度最佳移动广告平台奖
- MySQL重做日志文件放在磁盘_重做日志文件
- 台式机和台式计算机的区别,台式机和一体机区别是什么
- pytest学习:setup、teardown、setup_class、teardown_class的区别
- 加密算法之RSA算法
- 【案例设计】音频可视化 解析与设计
- 软件不能用Surface Pro触控笔 微软这有解决办法
- 三、nginx信号控制
- Python 视频转换为图片 与 图片转换为视频
- ABB机器人学习笔记(七)-机器人编程
- Cruzer Profile 原理分析
- mysql设置初始密码(linux)