使用HttpClient调用接口的实例讲解
时间:2019-04-07
本文章向大家介绍使用HttpClient调用接口的实例讲解,主要包括使用HttpClient调用接口的实例讲解使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
一,编写返回对象
public class HttpResult { // 响应的状态码 private int code; // 响应的响应体 private String body; get/set… }
二,封装HttpClient
package cn.xxxxxx.httpclient; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.utils.URIBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; public class APIService { private CloseableHttpClient httpClient; public APIService() { // 1 创建HttpClinet,相当于打开浏览器 this.httpClient = HttpClients.createDefault(); } /** * 带参数的get请求 * * @param url * @param map * @return * @throws Exception */ public HttpResult doGet(String url, Map<String, Object> map) throws Exception { // 声明URIBuilder URIBuilder uriBuilder = new URIBuilder(url); // 判断参数map是否为非空 if (map != null) { // 遍历参数 for (Map.Entry<String, Object> entry : map.entrySet()) { // 设置参数 uriBuilder.setParameter(entry.getKey(), entry.getValue().toString()); } } // 2 创建httpGet对象,相当于设置url请求地址 HttpGet httpGet = new HttpGet(uriBuilder.build()); // 3 使用HttpClient执行httpGet,相当于按回车,发起请求 CloseableHttpResponse response = this.httpClient.execute(httpGet); // 4 解析结果,封装返回对象httpResult,相当于显示相应的结果 // 状态码 // response.getStatusLine().getStatusCode(); // 响应体,字符串,如果response.getEntity()为空,下面这个代码会报错,所以解析之前要做非空的判断 // EntityUtils.toString(response.getEntity(), "UTF-8"); HttpResult httpResult = null; // 解析数据封装HttpResult if (response.getEntity() != null) { httpResult = new HttpResult(response.getStatusLine().getStatusCode(), EntityUtils.toString(response.getEntity(), "UTF-8")); } else { httpResult = new HttpResult(response.getStatusLine().getStatusCode(), ""); } // 返回 return httpResult; } /** * 不带参数的get请求 * * @param url * @return * @throws Exception */ public HttpResult doGet(String url) throws Exception { HttpResult httpResult = this.doGet(url, null); return httpResult; } /** * 带参数的post请求 * * @param url * @param map * @return * @throws Exception */ public HttpResult doPost(String url, Map<String, Object> map) throws Exception { // 声明httpPost请求 HttpPost httpPost = new HttpPost(url); // 判断map不为空 if (map != null) { // 声明存放参数的List集合 List<NameValuePair> params = new ArrayList<NameValuePair>(); // 遍历map,设置参数到list中 for (Map.Entry<String, Object> entry : map.entrySet()) { params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString())); } // 创建form表单对象 UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "UTF-8"); // 把表单对象设置到httpPost中 httpPost.setEntity(formEntity); } // 使用HttpClient发起请求,返回response CloseableHttpResponse response = this.httpClient.execute(httpPost); // 解析response封装返回对象httpResult HttpResult httpResult = null; if (response.getEntity() != null) { httpResult = new HttpResult(response.getStatusLine().getStatusCode(), EntityUtils.toString(response.getEntity(), "UTF-8")); } else { httpResult = new HttpResult(response.getStatusLine().getStatusCode(), ""); } // 返回结果 return httpResult; } /** * 不带参数的post请求 * * @param url * @return * @throws Exception */ public HttpResult doPost(String url) throws Exception { HttpResult httpResult = this.doPost(url, null); return httpResult; } /** * 带参数的Put请求 * * @param url * @param map * @return * @throws Exception */ public HttpResult doPut(String url, Map<String, Object> map) throws Exception { // 声明httpPost请求 HttpPut httpPut = new HttpPut(url); // 判断map不为空 if (map != null) { // 声明存放参数的List集合 List<NameValuePair> params = new ArrayList<NameValuePair>(); // 遍历map,设置参数到list中 for (Map.Entry<String, Object> entry : map.entrySet()) { params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString())); } // 创建form表单对象 UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "UTF-8"); // 把表单对象设置到httpPost中 httpPut.setEntity(formEntity); } // 使用HttpClient发起请求,返回response CloseableHttpResponse response = this.httpClient.execute(httpPut); // 解析response封装返回对象httpResult HttpResult httpResult = null; if (response.getEntity() != null) { httpResult = new HttpResult(response.getStatusLine().getStatusCode(), EntityUtils.toString(response.getEntity(), "UTF-8")); } else { httpResult = new HttpResult(response.getStatusLine().getStatusCode(), ""); } // 返回结果 return httpResult; } /** * 带参数的Delete请求 * * @param url * @param map * @return * @throws Exception */ public HttpResult doDelete(String url, Map<String, Object> map) throws Exception { // 声明URIBuilder URIBuilder uriBuilder = new URIBuilder(url); // 判断参数map是否为非空 if (map != null) { // 遍历参数 for (Map.Entry<String, Object> entry : map.entrySet()) { // 设置参数 uriBuilder.setParameter(entry.getKey(), entry.getValue().toString()); } } // 2 创建httpGet对象,相当于设置url请求地址 HttpDelete httpDelete = new HttpDelete(uriBuilder.build()); // 3 使用HttpClient执行httpGet,相当于按回车,发起请求 CloseableHttpResponse response = this.httpClient.execute(httpDelete); // 4 解析结果,封装返回对象httpResult,相当于显示相应的结果 // 状态码 // response.getStatusLine().getStatusCode(); // 响应体,字符串,如果response.getEntity()为空,下面这个代码会报错,所以解析之前要做非空的判断 // EntityUtils.toString(response.getEntity(), "UTF-8"); HttpResult httpResult = null; // 解析数据封装HttpResult if (response.getEntity() != null) { httpResult = new HttpResult(response.getStatusLine().getStatusCode(), EntityUtils.toString(response.getEntity(), "UTF-8")); } else { httpResult = new HttpResult(response.getStatusLine().getStatusCode(), ""); } // 返回 return httpResult; } }
三,调用接口
package cn.xxxxxx.httpclient.test; import java.util.HashMap; import java.util.Map; import org.junit.Before; import org.junit.Test; import cn.itcast.httpclient.APIService; import cn.itcast.httpclient.HttpResult; public class APIServiceTest { private APIService apiService; @Before public void init() { this.apiService = new APIService(); } // 查询 @Test public void testQueryItemById() throws Exception { // http://manager.aaaaaa.com/rest/item/interface/{id} String url = "http://manager.aaaaaa.com/rest/item/interface/42"; HttpResult httpResult = this.apiService.doGet(url); System.out.println(httpResult.getCode()); System.out.println(httpResult.getBody()); } // 新增 @Test public void testSaveItem() throws Exception { // http://manager.aaaaaa.com/rest/item/interface/{id} String url = "http://manager.aaaaaa.com/rest/item/interface"; Map<String, Object> map = new HashMap<String, Object>(); // title=测试RESTful风格的接口&price=1000&num=1&cid=888&status=1 map.put("title", "测试APIService调用新增接口"); map.put("price", "1000"); map.put("num", "1"); map.put("cid", "666"); map.put("status", "1"); HttpResult httpResult = this.apiService.doPost(url, map); System.out.println(httpResult.getCode()); System.out.println(httpResult.getBody()); } // 修改 @Test public void testUpdateItem() throws Exception { // http://manager.aaaaaa.com/rest/item/interface/{id} String url = "http://manager.aaaaaa.com/rest/item/interface"; Map<String, Object> map = new HashMap<String, Object>(); // title=测试RESTful风格的接口&price=1000&num=1&cid=888&status=1 map.put("title", "测试APIService调用修改接口"); map.put("id", "44"); HttpResult httpResult = this.apiService.doPut(url, map); System.out.println(httpResult.getCode()); System.out.println(httpResult.getBody()); } // 删除 @Test public void testDeleteItemById() throws Exception { // http://manager.aaaaaa.com/rest/item/interface/{id} String url = "http://manager.aaaaaa.com/rest/item/interface/44"; HttpResult httpResult = this.apiService.doDelete(url, null); System.out.println(httpResult.getCode()); System.out.println(httpResult.getBody()); } }
以上这篇使用HttpClient调用接口的实例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
- AI技术五年内必将颠覆现有医疗领域?
- 初探ReactJS.NET 开发
- 详解使用hadoop2.6.0搭建5个节点的分布式集群(附代码)
- Net Framework 2.0 事务处理
- Mono 4.0 Mac上运行asp.net mvc 5.2.3
- 电脑、打印机不归,牵出“无人车第一案”
- VS 2005 文本编码小技巧
- 混搭.NET技术
- 修改终端服务器的最大连接数
- 跨平台移动开发UI语言 -XAML
- S-shortcodes:WordPress短代码形式美化框插件下载
- 服务器同时存在1.1和2.0程序注意事项
- Flash/Flex学习笔记(44):万有引力与粒子系统
- 代码重写WordPress网页标题为“原网页标题|网站名”的形式
- JavaScript 教程
- JavaScript 编辑工具
- JavaScript 与HTML
- JavaScript 与Java
- JavaScript 数据结构
- JavaScript 基本数据类型
- JavaScript 特殊数据类型
- JavaScript 运算符
- JavaScript typeof 运算符
- JavaScript 表达式
- JavaScript 类型转换
- JavaScript 基本语法
- JavaScript 注释
- Javascript 基本处理流程
- Javascript 选择结构
- Javascript if 语句
- Javascript if 语句的嵌套
- Javascript switch 语句
- Javascript 循环结构
- Javascript 循环结构实例
- Javascript 跳转语句
- Javascript 控制语句总结
- Javascript 函数介绍
- Javascript 函数的定义
- Javascript 函数调用
- Javascript 几种特殊的函数
- JavaScript 内置函数简介
- Javascript eval() 函数
- Javascript isFinite() 函数
- Javascript isNaN() 函数
- parseInt() 与 parseFloat()
- escape() 与 unescape()
- Javascript 字符串介绍
- Javascript length属性
- javascript 字符串函数
- Javascript 日期对象简介
- Javascript 日期对象用途
- Date 对象属性和方法
- Javascript 数组是什么
- Javascript 创建数组
- Javascript 数组赋值与取值
- Javascript 数组属性和方法
- PHP多进程简单实例小结
- 解决laravel5中auth用户登录其他页面获取不到登录信息的问题
- Yii框架学习笔记之应用组件操作示例
- laravel 之 Eloquent 模型修改器和序列化示例
- TP5框架请求响应参数实例分析
- laravel 模型查询按照whereIn排序的示例
- 解决在laravel中auth建立时候遇到的问题
- php array 转json及java 转换 json数据格式操作示例
- Thinkphp5 如何隐藏入口文件index.php(URL重写)
- 在Laravel中使用GuzzleHttp调用第三方服务的API接口代码
- thinkphp5使html5实现动态跳转的例子
- php 自定义函数实现将数据 以excel 表格形式导出示例
- 解决tp5在nginx下修改配置访问的问题
- 在PHP中实现使用Guzzle执行POST和GET请求
- c 语言函数指针之回调函数