Restful Api调用工具类
RestfulHttpClient.java
package pres.lnk.utils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* <p>RestfulApi请求工具</p>
* <a href="http://blog.csdn.net/lnktoking/article/details/79174187">使用说明</a>
*
* @author lnk
*/
public class RestfulHttpClient {
/**
* 全局默认请求头
*/
private static final Map<String, String> defaultHeaders = new HashMap<>();
/**
* 全局连接初始化器
*/
private static List<URLConnectionInitializer> initializers;
private static final String charset = "UTF-8";
private static final int readTimeout = 60000;
private static final int connectTimeout = 60000;
public static final String METHOD_GET = "GET";
public static final String METHOD_POST = "POST";
public static final String METHOD_PUT = "PUT";
public static final String METHOD_PATCH = "PATCH";
public static final String METHOD_DELETE = "DELETE";
private RestfulHttpClient() {
}
/**
* 发起请求
*
* @param method 请求方式:GET、POST、PUT、PATCH、DELETE
* @param url 请求url
* @param body 请求体body
* @throws IOException
*/
public static HttpResponse request(String method, String url, Object body) throws IOException {
return request(method, url, body, defaultHeaders);
}
/**
* 发起请求
*
* @param method 请求方式:GET、POST、PUT、PATCH、DELETE
* @param url 请求url
* @param body 请求体body
* @param headers 请求头
* @throws IOException
*/
public static HttpResponse request(String method, String url, Object body, Map<String, String> headers) throws IOException {
return getClient(url).method(method).body(body).headers(headers).request();
}
/**
* 获取请求客户端
*
* @param url
* @return
*/
public static HttpClient getClient(String url) {
return new HttpClient(url);
}
/**
* 添加全局请求连接初始化器
*
* @param initializer
*/
public static void addInitializer(URLConnectionInitializer initializer) {
if (initializer == null) {
throw new NullPointerException("不能添加空的连接初始化器");
}
if (initializers == null) {
initializers = new ArrayList<>();
}
initializers.add(initializer);
}
/**
* 请求客户端
*/
public static class HttpClient {
private Map<String, String> headers;
private int readTimeout = RestfulHttpClient.readTimeout;
private int connectTimeout = RestfulHttpClient.connectTimeout;
private String method = METHOD_GET;
private String url;
private Map<String, String> pathParams;
private Map<String, String> queryParams;
private Map<String, String> postParams;
private Object body;
private HttpResponse response;
private List<URLConnectionInitializer> initializers;
public HttpClient(String url) {
if (StringUtils.isBlank(url)) {
throw new IllegalArgumentException("请求地址不能为空");
}
this.url = url;
headers = new HashMap<>();
pathParams = new HashMap<>();
queryParams = new HashMap<>();
postParams = new HashMap<>();
headers.putAll(defaultHeaders);
initializers = RestfulHttpClient.initializers;
}
public HttpClient get() {
method = METHOD_GET;
return this;
}
public HttpClient post() {
method = METHOD_POST;
return this;
}
public HttpClient put() {
method = METHOD_PUT;
return this;
}
public HttpClient patch() {
method = METHOD_PATCH;
return this;
}
public HttpClient delete() {
method = METHOD_DELETE;
return this;
}
/**
* 添加请求头
*/
public HttpClient addHeader(String key, String value) {
this.headers.put(key, value);
return this;
}
/**
* 批量添加请求头
*/
public HttpClient addHeaders(Map<String, String> headers) {
this.headers.putAll(headers);
return this;
}
/**
* 设置读取超时时间
*/
public HttpClient readTimeout(int readTimeout) {
this.readTimeout = readTimeout;
return this;
}
/**
* 设置连接超时时间
*/
public HttpClient connectTimeout(int connectTimeout) {
this.connectTimeout = connectTimeout;
return this;
}
/**
* 重置请求头
*/
public HttpClient headers(Map<String, String> headers) {
this.headers.clear();
this.headers.putAll(defaultHeaders);
return addHeaders(headers);
}
/**
* 设置请求方式,默认:GET
*/
public HttpClient method(String method) {
if (StringUtils.isBlank(method)) {
throw new IllegalArgumentException("请求方式不能为空");
}
//请求方式不做限制
// if(!ArrayUtils.contains(new String[]{METHOD_GET, METHOD_POST, METHOD_PUT, METHOD_PATCH, METHOD_DELETE}, method.toUpperCase())){
// throw new IllegalArgumentException("请求方式设置错误,不能设置为:" + method);
// }
this.method = method.toUpperCase();
return this;
}
/**
* 设置请求地址,可带path参数
* 如:/user/{id}
*/
public HttpClient url(String url) {
this.url = url;
return this;
}
/**
* 设置请求地址参数,替换url上的参数
* 如:/user/{id} 上的{id}
*/
public HttpClient pathParams(Map<String, String> pathParams) {
this.pathParams.putAll(pathParams);
return this;
}
/**
* 添加请求地址参数,替换url上的参数
* 如:/user/{id} 上的{id}
*/
public HttpClient addPathParam(String key, String value) {
this.pathParams.put(key, value);
return this;
}
/**
* 设置url请求参数,url问号后面的参数
*/
public HttpClient queryParams(Map<String, String> queryParams) {
this.queryParams.putAll(queryParams);
return this;
}
/**
* 添加url请求参数,url问号后面的参数
*/
public HttpClient addQueryParam(String key, String value) {
this.queryParams.put(key, value);
return this;
}
/**
* 设置表单参数,与body参数冲突,只能设置其中一个,优先使用body
*/
public HttpClient postParams(Map<String, String> postParams) {
this.postParams.putAll(postParams);
return this;
}
/**
* 添加表单参数
*/
public HttpClient addPostParam(String key, String value) {
this.postParams.put(key, value);
return this;
}
/**
* 设置请求体body,与post参数冲突,只能设置其中一个
*/
public HttpClient body(Object body) {
this.body = body;
return this;
}
/**
* 获取最终的请求地址
*
* @return
*/
public String getRequestUrl() {
return transformUrl(this.url, pathParams, queryParams);
}
/**
* 发起请求
*
* @return
* @throws IOException
*/
public HttpResponse request() throws IOException {
response = RestfulHttpClient.request(this);
return response;
}
/**
* 添加请求连接初始化器
*
* @param initializer
*/
public HttpClient addInitializer(URLConnectionInitializer initializer) {
if (initializer == null) {
throw new NullPointerException("不能添加空的连接初始化器");
}
if (initializers == null) {
initializers = new ArrayList<>();
}
initializers.add(initializer);
return this;
}
public Map<String, String> getHeaders() {
return headers;
}
public int getReadTimeout() {
return readTimeout;
}
public int getConnectTimeout() {
return connectTimeout;
}
public String getMethod() {
return method;
}
public String getUrl() {
return url;
}
public Map<String, String> getQueryParams() {
return queryParams;
}
public Map<String, String> getPathParams() {
return pathParams;
}
public Map<String, String> getPostParams() {
return postParams;
}
public <T> T getBody() {
return (T) body;
}
public HttpResponse getResponse() {
return response;
}
}
/**
* 请求响应结果
*/
public static class HttpResponse {
private int code;
private Map<String, List<String>> headers;
private String requestUrl;
private String content;
public HttpResponse(int code, Map<String, List<String>> headers, String requestUrl, String content) {
this.code = code;
this.headers = headers;
this.requestUrl = requestUrl;
this.content = content;
}
public <T> T getContent(Class<T> clz) throws IOException {
if (StringUtils.isNotBlank(content)) {
return new ObjectMapper().readValue(content, clz);
}
return null;
}
/**
* 获取响应状态码
*/
public int getCode() {
return code;
}
/**
* 获取响应头
*/
public Map<String, List<String>> getHeaders() {
return headers;
}
/**
* 获取最后请求地址
*/
public String getRequestUrl() {
return requestUrl;
}
/**
* 获取响应内容
*/
public String getContent() {
return content;
}
}
/**
* 发起请求
*
* @throws IOException
*/
private static HttpResponse request(HttpClient client) throws IOException {
HttpURLConnection con = instance(client);
if (METHOD_GET.equalsIgnoreCase(client.getMethod())) {
//GET请求,不用发请求体
return readResponse(con);
}
String requestBody = null;
if (isPrimitiveOrWrapClzOrStr(client.getBody())) {
requestBody = client.getBody().toString();
} else if (client.getBody() != null) {
requestBody = new ObjectMapper().writeValueAsString(client.getBody());
if (!client.getHeaders().containsKey("Content-Type")) {
//设置请求媒体类型为json提交
con.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
}
} else if (client.getPostParams() != null && !client.getPostParams().isEmpty()) {
requestBody = toUrlParams(client.getPostParams());
}
con.setDoOutput(true);
con.setDoInput(true);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(con.getOutputStream(), charset));
if (requestBody != null) {
//写入请求内容
bw.write(requestBody);
}
bw.close();
return readResponse(con);
}
/**
* 判断是否是字符串或基本类型或包装类型
*
* @param o
* @return
*/
private static boolean isPrimitiveOrWrapClzOrStr(Object o) {
if (o == null) {
return false;
} else if (o instanceof String) {
//是字符串类型
return true;
} else if (o.getClass().isPrimitive()) {
//是基本类型
return true;
} else {
try {
//是包装类型
return ((Class) o.getClass().getField("TYPE").get(null)).isPrimitive();
} catch (Exception e) {
return false;
}
}
}
/**
* 读取响应结果
*
* @param con
* @return
* @throws IOException
*/
private static HttpResponse readResponse(HttpURLConnection con) throws IOException {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));
StringBuilder sb = new StringBuilder();
String read = null;
while ((read = br.readLine()) != null) {
sb.append(read);
sb.append("\n");
}
br.close();
return new HttpResponse(con.getResponseCode(), con.getHeaderFields(),
con.getURL().toString(), sb.toString());
} finally {
con.disconnect();
}
}
/**
* 初始化请求连接
*
* @param client
* @return
* @throws IOException
*/
private static HttpURLConnection instance(HttpClient client) throws IOException {
URL u = new URL(client.getRequestUrl());
HttpURLConnection con = (HttpURLConnection) u.openConnection();
con.setReadTimeout(client.getReadTimeout());
con.setConnectTimeout(client.getConnectTimeout());
con.setRequestMethod(client.getMethod());
Map<String, String> headers = client.getHeaders();
if (headers != null && !headers.isEmpty()) {
for (String key : headers.keySet()) {
con.setRequestProperty(key, headers.get(key));
}
}
List<URLConnectionInitializer> initializers = client.initializers;
if (initializers != null && !initializers.isEmpty()) {
for (URLConnectionInitializer initializer : initializers) {
HttpURLConnection init = initializer.init(con, client);
if (init != null) {
con = init;
}
}
}
return con;
}
/**
* 处理url的参数
* 如:/user/{id},将id转成值
*
* @param url
* @param pathParams 地址参数
* @param queryParams 请求参数
* @return
*/
private static String transformUrl(String url, Map<String, String> pathParams, Map<String, String> queryParams) {
if (pathParams != null && !pathParams.isEmpty()) {
for (String key : pathParams.keySet()) {
url = url.replaceAll("\\{" + key + "\\}", pathParams.get(key));
}
}
if (queryParams != null && !queryParams.isEmpty()) {
if (url.indexOf("?") > 0) {
url += "&" + toUrlParams(queryParams);
} else {
url += "?" + toUrlParams(queryParams);
}
}
return url;
}
/**
* 将map参数转成url参数形式:name1=value2&name2=value2...
*
* @param paras
* @return
*/
public static String toUrlParams(Map<String, String> paras) {
if (paras != null && !paras.isEmpty()) {
StringBuffer urlParams = new StringBuffer();
for (String k : paras.keySet()) {
urlParams.append(k + "=" + paras.get(k) + "&");
}
if (urlParams.length() > 0) {
return urlParams.substring(0, urlParams.length() - 1);
}
}
return null;
}
/**
* 获取全局默认请求headers设置
*
* @return
*/
public static Map<String, String> getDefaultHeaders() {
return defaultHeaders;
}
/**
* 设置默认全局默认请求headers
*
* @param headers
* @return
*/
public static Map<String, String> setDefaultHeaders(Map<String, String> headers) {
defaultHeaders.clear();
defaultHeaders.putAll(headers);
return getDefaultHeaders();
}
/**
* 连接初始化器
*/
public interface URLConnectionInitializer {
/**
* 初始化http请求连接对象
*
* @param connection
* @return
*/
HttpURLConnection init(HttpURLConnection connection, HttpClient client);
}
public static void main(String[] args) throws IOException {
String url = "http://localhost:8081/user/{id}";
RestfulHttpClient.HttpResponse response = getClient(url)
.post() //设置post请求
.addHeader("token", "tokenValue") //添加header
.addPathParam("id", "2") //设置url路径参数
.addQueryParam("test", "value") //设置url请求参数
.request(); //发起请求
System.out.println(response.getCode()); //响应状态码
System.out.println(response.getRequestUrl());//最终发起请求的地址
if (response.getCode() == 200) {
//请求成功
System.out.println(response.getContent()); //响应内容
}
}
}
TrustAllHttpsInitializer.java
package pres.lnk.utils;
import javax.net.ssl.*;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
/**
* 信任所有https的请求
* 注意:使用该初始器化之后会存在安全认证风险,慎用
* @Author lnk
* @Date 2018/5/29
*/
public class TrustAllHttpsInitializer implements RestfulHttpClient.URLConnectionInitializer {
@Override
public HttpURLConnection init(HttpURLConnection connection, RestfulHttpClient.HttpClient client) {
String protocol = connection.getURL().getProtocol();
if ("https".equalsIgnoreCase(protocol)) {
HttpsURLConnection https = (HttpsURLConnection) connection;
trustAllHosts(https);
https.setHostnameVerifier(DO_NOT_VERIFY);
return https;
}
return connection;
}
/**
* 覆盖java默认的证书验证
*/
private static final TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s)
throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s)
throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}};
/**
* 设置不验证主机
*/
private static final HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
/**
* 信任所有
* @param connection
* @return
*/
private static SSLSocketFactory trustAllHosts(HttpsURLConnection connection) {
SSLSocketFactory oldFactory = connection.getSSLSocketFactory();
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, null);
SSLSocketFactory newFactory = sc.getSocketFactory();
connection.setSSLSocketFactory(newFactory);
} catch (Exception e) {
e.printStackTrace();
}
return oldFactory;
}
public static void main(String[] args) throws IOException {
String url = "https://b2b.10086.cn/b2b/main/viewNoticeContent.html?noticeBean.id=";
RestfulHttpClient.HttpResponse response = RestfulHttpClient.getClient(url)
.addInitializer(new TrustAllHttpsInitializer())
.request(); //发起请求
System.out.println(response.getCode()); //响应状态码
System.out.println(response.getRequestUrl());//最终发起请求的地址
if(response.getCode() == 200){
//请求成功
System.out.println(response.getContent()); //响应内容
}
}
}
Restful Api调用工具类的更多相关文章
- Hitchhiker 是一款开源的 Restful Api 测试工具
Hitchhiker 是一款开源的 Restful Api 测试工具 开源API测试工具 Hitchhiker v0.4更新 - 没有做不到,只有想不到 Hitchhiker 是一款开源的 Restf ...
- 开源的 Restful Api 集成测试工具 Hitchhiker
Hitchhiker 是一款开源的 Restful Api 集成测试工具,你可以在轻松部署到本地,和你的team成员一起管理Api. 先上图看看: 简单介绍 背景是Team在开发一些Api,这些Api ...
- Spring 远程调用工具类RestTemplateUtils
Spring 远程调用Rest服务工具类,包含Get.Post.Put.Delete四种调用方式. 依赖jar <dependency> <groupId>org.spring ...
- PostMan 快快走开, ApiFox 来了, ApiFox 强大的Api调用工具
简介 为什么要用ApiFox呢, 一般现在程序员开发测试, 一般都是PostMan, PostWoman等Api调用工具, 我之前也是一直在用, 但是今天我发现了一款相比于Postman更加好用的工具 ...
- RestTemplate---Spring提供的轻量Http Rest 风格API调用工具
前言 今天在学习Spring Cloud的过程中无意发现了 RestTemplate 这个Spring 提供的Http Rest风格接口之间调用的模板工具类,感觉比Apache提供的HttpClien ...
- hibernate框架学习第二天:核心API、工具类、事务、查询、方言、主键生成策略等
核心API Configuration 描述的是一个封装所有配置信息的对象 1.加载hibernate.properties(非主流,早期) Configuration conf = new Conf ...
- spring -mvc service层调用工具类配置
在service层时调用工具类时服务返回工具类对象为空 在此工具类上加上@Component注解就可以了 @Component:把普通pojo实例化到spring容器中,相当于配置文件中的 <b ...
- RESTful API测试工具
Postman Postman是一个Chrome APP,可以直接通过Chrome商店安装(需F墙,推荐修改hosts的方法,简便快捷有效) 其截图如下,非常漂亮 Aoizza Web APP,点击访 ...
- Chrome Restful Api 测试工具 Postman-REST-Client离线安装包下载,Axure RP Extension for Chrome离线版下载
[Postman for Chrome 离线下载] Postman-REST-Client离线安装包,可直接在Chrome浏览器本地安装使用,可模拟各种http请求,Restful Api测试, CS ...
随机推荐
- JVM系列大纲
本系列主要分析JVM主要功能要点,初步大纲如下,会根据写作情况进行细化,目的在于梳理JVM的知识体系,具体分析文章会陆续发布. [JVM]类加载机制(1) [JVM]Java内存区域(2) [JVM] ...
- [CSP-S模拟测试]:任务分配(最短路+贪心+DP)
题目传送门(内部题149) 输入格式 每个测试点第一行为四个正整数$n,b,s,m$,含义如题目所述. 接下来$m$行,每行三个非负整数$u,v,l$,表示从点$u$到点$v$有一条权值为$l$的有向 ...
- Java中的基本数据类型和引用类型
一.基本数据类型: byte:Java中最小的数据类型,在内存中占8位(bit),即1个字节,取值范围-128~127,默认值0 short:短整型,在内存中占16位,即2个字节,取值范围-32768 ...
- 邻居子系统 之 邻居表的初始化neigh_table_init
概述 邻居子系统支持多种实现,例如ARP,ND等,这些实现需要在其初始化的时候,调用neigh_table_init将邻居表项添加到全局邻居子系统数组中,并对实例中的字段(如hash,定时器等)进行相 ...
- oracle中监听程序当前无法识别连接描述符中请求服务 的解决方法
早上同事用PL/SQL连接虚拟机中的Oracle数据库,发现又报了“ORA-12514 TNS 监听程序当前无法识别连接描述符中请求服务”错误,帮其解决后,发现很多人遇到过这样的问题,因此写着这里. ...
- 搭建Java服务器,并且实现远程安全访问linux系统
1.通过ssh实现安全远程访问linux系统 ssh :secure shell 加密: 1. 对称加密 (加密密钥与解密密钥相同) des ...
- Java计算器的图形界面应用程序
JAVA计算器的图形界面应用程序 题目简介: 整体分析: 实验代码: /*部分使用插件做界面*/ import java.awt.EventQueue; import javax.swing.JB ...
- MySQL 按照数据库表字段动态排序 查询列表信息
MySQL 按照数据库表字段动态排序 查询列表信息 背景描述 项目中数据列表分页展示的时候,前端使用的Table组件,每列自带对当前页的数据进行升序或者降序的排序. 但是客户期望:随机点击某一列的时候 ...
- JS事件中级 --- 拖拽
http://bbs.zhinengshe.com/thread-1200-1-1.html 要求:实现div块的拖拽 原理:拖拽过程中鼠标点和div块的相对位置保持不变. 需要理解三点: 1. 为什 ...
- document.documentElement 和 document.body
MDN : The Document.documentElement read-only property returns the Element that is the root element o ...