这里总结一下使用HttpClient访问外部接口的用法。后期如果发现有什么缺陷会更改。欢迎读者指出此方法的不足之处。

首先,创建一个返回实体:

public class HttpResult {
// 响应的状态码
private int code; // 响应的响应体
private String body; public HttpResult(int code, String body) {
this.code = code;
this.body = body;
}
//省略get/set
}

创建一个HttpClientUtil:

public class HttpClientUtil {

    private static CloseableHttpClient httpClient =  HttpClients.createDefault();	//用static实现单例,此处不完善,当多线程时会出现问题。

    /**
* 带参数的get请求
*
* @param url
* @param map
* @return
* @throws Exception
*/
public static 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 = 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 static HttpResult doGet(String url) throws Exception {
HttpResult httpResult = doGet(url, null);
return httpResult;
} /**
* 带参数的post请求
*
* @param url
* @return
* @throws Exception
*/
public static HttpResult doPost(String url, Map<String, Object> reqMap, Map<String,String> headersMap) throws Exception {
// 声明httpPost请求
HttpPost httpPost = new HttpPost(url);
for (Map.Entry<String, String> entry: headersMap.entrySet())
httpPost.addHeader(entry.getKey(), entry.getValue()); // 判断map不为空
if (reqMap != null) { // 创建form表单对象
StringEntity formEntity = new StringEntity(JSON.toJSONString(reqMap), "UTF-8"); // 把表单对象设置到httpPost中
httpPost.setEntity(formEntity);
} // 使用HttpClient发起请求,返回response
CloseableHttpResponse response = 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 static HttpResult doPost(String url) throws Exception {
HttpResult httpResult = doPost(url, null,null);
return httpResult;
} /**
* 带参数的Put请求
*
* @param url
* @param map
* @return
* @throws Exception
*/
public static 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 = 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 static 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 = 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;
} /**
* 返回常用请求头
* @return
*/
public static Map<String, String> commentHeader(){
Map<String, String> map = new HashMap<>();
map.put("Content-Type", "application/json");
return map;
}
}

测试一下:

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 { // 查询
@Test
public void testGet() throws Exception {
// http://manager.aaaaaa.com/rest/item/interface/{id} String url = "http://manager.aaaaaa.com/rest/item/interface/42"; HttpResult httpResult = HttpClientUtil.doGet(url); System.out.println(httpResult.getCode());
System.out.println(httpResult.getBody()); } // 查询
@Test
public void testPost() throws Exception {
//设置参数
Map reqMap = new HashMap();
reqMap.put("distCode", arsArg.getDistCode());
HttpResult httpResult = null;
try {
//RestUrlsCommons.RMDS_DISTRICT_FINDBYDISTCODE为url
//reqMap:请求参数
//HttpClientUtil.commentHeader():请求头
httpResult = HttpClientUtil.doPost(RestUrlsCommons.RMDS_DISTRICT_FINDBYDISTCODE, reqMap, HttpClientUtil.commentHeader());
} catch (Exception e) {
e.printStackTrace();
} System.out.println(httpResult.getCode());
System.out.println(httpResult.getBody());
} }

参考资料:使用HttpClient调用接口

使用HttpClient访问接口(Rest接口和普通接口)的更多相关文章

  1. java实现利用httpclient访问接口

    HTTP协议时Internet上使用的很多也很重要的一个协议,越来越多的java应用程序需要通过HTTP协议来访问网络资源. HTTPClient提供的主要功能: 1.实现了所有HTTP的方法(GET ...

  2. 使用httpclient访问NLP应用接口例子

    参考网址: http://yuzhinlp.com/docs.html 接入前须知 接入条件 1.进入网站首页,点击注册成为语知科技用户 2.注册完成后,系统将提供语知科技用户唯一标识APIKey,并 ...

  3. 【经验随笔】Java通过代理访问互联网平台提供的WebService接口的一种方法

    背景 通常有两点原因需要通过代理访问互联网平台的提供的WebService接口: 1. 在公司企业内网访问外部互联网平台发布的接口,公司要求通过代理访问外网. 2. 频繁访问平台接口,IP被平台封了, ...

  4. Java基础进阶:多态与接口重点摘要,类和接口,接口特点,接口详解,多态详解,多态中的成员访问特点,多态的好处和弊端,多态的转型,多态存在的问题,附重难点,代码实现源码,课堂笔记,课后扩展及答案

    多态与接口重点摘要 接口特点: 接口用interface修饰 interface 接口名{} 类实现接口用implements表示 class 类名 implements接口名{} 接口不能实例化,可 ...

  5. cxf整合spring发布rest服务 httpclient访问服务

    1.创建maven web项目并添加依赖 pom.xml <properties> <webVersion>3.0</webVersion> <cxf.ver ...

  6. Surface Pro 4 和 Surface Book 使用名为 Surface UEFI(统一可扩展固件接口)的新固件接口

    Surface Pro 4 和 Surface Book 使用名为 Surface UEFI(统一可扩展固件接口)的新固件接口.Surface UEFI 提供新功能,如启动更快速.安全性更高.可替换 ...

  7. PHP做APP接口时,如何保证接口的安全性??????????

    PHP做APP接口时,如何保证接口的安全性? 1.当用户登录APP时,使用https协议调用后台相关接口,服务器端根据用户名和密码时生成一个access_key,并将access_key保存在sess ...

  8. java接口对接——别人调用我们接口获取数据

    java接口对接——别人调用我们接口获取数据,我们需要在我们系统中开发几个接口,给对方接口规范文档,包括访问我们的接口地址,以及入参名称和格式,还有我们的返回的状态的情况, 接口代码: package ...

  9. C#显示接口实现和隐式接口实现

    在项目中可能会遇到显示接口实现和隐式接口实现.什么意思呢?简单来说使用接口名作为方法名的前缀,这称为“显式接口实现”:传统的实现方式,称为“隐式接口实现”.隐式接口实现如下: interface IS ...

随机推荐

  1. 数据库系统概论(新技术篇)--中国人民大学【第13讲】KEY-VALUE数据库(键值对数据库)

    市面上主流的分布式文件系统(FS): (Hadoop的)HDFS,(Google的)GFS     详见ppt   1.数据服务与键值对数据库: 数据服务:data serving数据服务:数据的简单 ...

  2. js实现时分秒毫秒计时器

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  3. django orm 基于双下划线的跨表查询

    一..基于双下划线的跨表查询(join实现) key:正向查询按字段,反向查询按表明小写 1.一对多跨表查询 查询在跨表中可以有两种方式,正向查询就是关键字段在你要搜索的表,没有关键字段就是反向查询 ...

  4. C++小工具

    1.Doxygen 从源代码生成文档.可以生成在线文档(HTML)和离线手册(以LATEX格式),还可以自动生成各种依赖关系图,继承关系图等.

  5. vue社区活跃整合

    ===框架===== Nuxt(vue ssr服务端渲染) Quasar Framework 一个可以搭建多平台响应式网站的框架 Weex 是一个使用 Web 开发体验来开发高性能原生应用的框架. = ...

  6. LeetCode 568. Maximum Vacation Days

    原题链接在这里:https://leetcode.com/problems/maximum-vacation-days/ 题目: LeetCode wants to give one of its b ...

  7. prototype、__proto__、constructor

    prototype:每个函数都有一个prototype属性,这个属性指向一个对象,这个对象叫原型对象. 作用:节约内存.扩展属性和方法.可以实现类之间的继承 __proto__:每个通过构造函数new ...

  8. ECMAScript6之Class

    1.Class的基本语法 1.1简介 基本上,ES6 的class可以看作只是一个语法糖,它的绝大部分功能,ES5 都可以做到,新的class写法只是让对象原型的写法更加清晰.更像面向对象编程的语法而 ...

  9. 导出OpenID为txt文件的方法

    导出OpenID为txt文件的方法 public function export(){ $shop = M("Shop"); $arr = $shop->field('ope ...

  10. spring boot 启动原理详细解析

    我们开发任何一个Spring Boot项目,都会用到如下的启动类 1 @SpringBootApplication 2 public class Application { 3 public stat ...