使用HttpClient访问接口(Rest接口和普通接口)
这里总结一下使用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接口和普通接口)的更多相关文章
- java实现利用httpclient访问接口
HTTP协议时Internet上使用的很多也很重要的一个协议,越来越多的java应用程序需要通过HTTP协议来访问网络资源. HTTPClient提供的主要功能: 1.实现了所有HTTP的方法(GET ...
- 使用httpclient访问NLP应用接口例子
参考网址: http://yuzhinlp.com/docs.html 接入前须知 接入条件 1.进入网站首页,点击注册成为语知科技用户 2.注册完成后,系统将提供语知科技用户唯一标识APIKey,并 ...
- 【经验随笔】Java通过代理访问互联网平台提供的WebService接口的一种方法
背景 通常有两点原因需要通过代理访问互联网平台的提供的WebService接口: 1. 在公司企业内网访问外部互联网平台发布的接口,公司要求通过代理访问外网. 2. 频繁访问平台接口,IP被平台封了, ...
- Java基础进阶:多态与接口重点摘要,类和接口,接口特点,接口详解,多态详解,多态中的成员访问特点,多态的好处和弊端,多态的转型,多态存在的问题,附重难点,代码实现源码,课堂笔记,课后扩展及答案
多态与接口重点摘要 接口特点: 接口用interface修饰 interface 接口名{} 类实现接口用implements表示 class 类名 implements接口名{} 接口不能实例化,可 ...
- cxf整合spring发布rest服务 httpclient访问服务
1.创建maven web项目并添加依赖 pom.xml <properties> <webVersion>3.0</webVersion> <cxf.ver ...
- Surface Pro 4 和 Surface Book 使用名为 Surface UEFI(统一可扩展固件接口)的新固件接口
Surface Pro 4 和 Surface Book 使用名为 Surface UEFI(统一可扩展固件接口)的新固件接口.Surface UEFI 提供新功能,如启动更快速.安全性更高.可替换 ...
- PHP做APP接口时,如何保证接口的安全性??????????
PHP做APP接口时,如何保证接口的安全性? 1.当用户登录APP时,使用https协议调用后台相关接口,服务器端根据用户名和密码时生成一个access_key,并将access_key保存在sess ...
- java接口对接——别人调用我们接口获取数据
java接口对接——别人调用我们接口获取数据,我们需要在我们系统中开发几个接口,给对方接口规范文档,包括访问我们的接口地址,以及入参名称和格式,还有我们的返回的状态的情况, 接口代码: package ...
- C#显示接口实现和隐式接口实现
在项目中可能会遇到显示接口实现和隐式接口实现.什么意思呢?简单来说使用接口名作为方法名的前缀,这称为“显式接口实现”:传统的实现方式,称为“隐式接口实现”.隐式接口实现如下: interface IS ...
随机推荐
- 团队第六次作业:Beta版本冲刺成绩汇总
一.作业题目 团队第六次作业:Beta版本冲刺 二.作业评分标准 博客评分规则(总分100)博客要求 1.冲刺博客每篇占20分.(3次) - (1) 各成员该天完成的工作,以及明天的任务安排(表格的形 ...
- C++负数类型转换,-1对256取模
最近在读C++ primer的时候,发现p32上写道:当我们赋给无符号类型一个超出它表示范围的值时,结果是初始值对无符号类型表示数值总数取模后的余数.因此,把-1赋值给8比特大小的unsigned c ...
- 【java异常】Unable to install breakpoint in
这个是断点失效,把那个断点双击清理掉就完了. 具体原因,以后再写.
- Scrapy笔记10- 动态配置爬虫
Scrapy笔记10- 动态配置爬虫 有很多时候我们需要从多个网站爬取所需要的数据,比如我们想爬取多个网站的新闻,将其存储到数据库同一个表中.我们是不是要对每个网站都得去定义一个Spider类呢? 其 ...
- LeetCode 568. Maximum Vacation Days
原题链接在这里:https://leetcode.com/problems/maximum-vacation-days/ 题目: LeetCode wants to give one of its b ...
- 安装sentry的几个命令
docker run -d --name sentry-redis redis docker run -d --name sentry-postgres -e POSTGRES_PASSWORD=se ...
- md5-js加密
JS-MD5加密/html页面使用 大家都知道,传输明文信息很不安全,尤其像密码.卡号等这些敏感私密的信息,更不能暴露出去.在这里给大家介绍一种在前端JS中的MD5加密算法(因为要匹配的后台数据是MD ...
- python paramiko模块简介及安装
一:简介 paramiko是用python语言写的一个模块,遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连接. 由于使用的是python这样的能够跨平台运行的语言,所以所有python支 ...
- selenium--高亮显示正在操作的元素
前戏 在进行web自动化的时候,如果我们想知道正在操作的元素,我们可以通过js的方式来实现 实战 from selenium import webdriver import unittest, tim ...
- 两次bfs求树的直径的正确性
结论:离树上任意点\(u\)最远的点一定是这颗树直径的一个端点. 证明: 若点\(u\)在树的直径上,设它与直径两个端点\(x,y\)的距离分别为\(S1\).\(S2\),若距离其最远的点\(v\) ...