一个java的http请求的封装工具类
java实现http请求的方法常用有两种,一种则是通过java自带的标准类HttpURLConnection去实现,另一种是通过apache的httpclient去实现。
本文用httpclient去实现,需要导入httpclient和httpcore两个jar包,测试时用的httpclient-4.5.1和httpcore-4.4.3。
HttpMethod.java
package demo; public enum HttpMethod {
GET, POST;
}
HttpHeader.java
package demo; import java.util.HashMap;
import java.util.Map; /**
* 请求头
*/
public class HttpHeader {
private Map<String, String> params = new HashMap<String, String>(); public HttpHeader addParam(String name, String value) {
this.params.put(name, value);
return this;
} public Map<String, String> getParams() {
return this.params;
}
}
HttpParamers.java
package demo; import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Set; import com.alibaba.fastjson.JSON; /**
* 请求参数
*/
public class HttpParamers {
private Map<String, String> params = new HashMap<String, String>();
private HttpMethod httpMethod;
private String jsonParamer = ""; public HttpParamers(HttpMethod httpMethod) {
this.httpMethod = httpMethod;
} public static HttpParamers httpPostParamers() {
return new HttpParamers(HttpMethod.POST);
} public static HttpParamers httpGetParamers() {
return new HttpParamers(HttpMethod.GET);
} public HttpParamers addParam(String name, String value) {
this.params.put(name, value);
return this;
} public HttpMethod getHttpMethod() {
return this.httpMethod;
} public String getQueryString(String charset) throws IOException {
if ((this.params == null) || (this.params.isEmpty())) {
return null;
}
StringBuilder query = new StringBuilder();
Set<Map.Entry<String, String>> entries = this.params.entrySet(); for (Map.Entry<String, String> entry : entries) {
String name = entry.getKey();
String value = entry.getValue();
query.append("&").append(name).append("=").append(URLEncoder.encode(value, charset));
}
return query.substring(1);
} public boolean isJson() {
return !isEmpty(this.jsonParamer);
} public Map<String, String> getParams() {
return this.params;
} public String toString() {
return "HttpParamers " + JSON.toJSONString(this);
} public String getJsonParamer() {
return this.jsonParamer;
} public void setJsonParamer() {
this.jsonParamer = JSON.toJSONString(this.params);
} private static boolean isEmpty(CharSequence cs) {
return (cs == null) || (cs.length() == 0);
}
}
HttpClient.java
package demo; import java.io.IOException;
import java.util.Map;
import java.util.Set; import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils; public class HttpClient {
public static final String DEFAULT_CHARSET = "UTF-8";
public static final String JSON_CONTENT_FORM = "application/json;charset=UTF-8";
public static final String CONTENT_FORM = "application/x-www-form-urlencoded;charset=UTF-8"; public static String doService(String url, HttpParamers paramers, HttpHeader header, int connectTimeout, int readTimeout) throws Exception {
HttpMethod httpMethod = paramers.getHttpMethod();
switch (httpMethod) {
case GET:
return doGet(url, paramers, header, connectTimeout, readTimeout);
case POST:
return doPost(url, paramers, header, connectTimeout, readTimeout);
}
return null;
} /**
* post方法
* @param url
* @param paramers
* @param header
* @param connectTimeout
* @param readTimeout
* @return
* @throws IOException
*/
public static String doPost(String url, HttpParamers paramers, HttpHeader header, int connectTimeout, int readTimeout) throws IOException {
String responseData = "";
CloseableHttpClient httpClient = null;
CloseableHttpResponse httpResponse = null;
try{
String query = null;
HttpPost httpPost = new HttpPost(url);
setHeader(httpPost, header);
if (paramers.isJson()) {
//json数据
httpPost.setHeader(HTTP.CONTENT_TYPE, JSON_CONTENT_FORM);
query = paramers.getJsonParamer();
} else {
//表单数据
httpPost.setHeader(HTTP.CONTENT_TYPE, CONTENT_FORM);
query = paramers.getQueryString(DEFAULT_CHARSET);
}
if(query != null){
HttpEntity reqEntity = new StringEntity(query);
httpPost.setEntity(reqEntity);
}
httpClient = HttpClients.createDefault();
httpResponse = httpClient.execute(httpPost);
HttpEntity resEntity = httpResponse.getEntity();
responseData = EntityUtils.toString(resEntity);
} catch (Exception e){
e.printStackTrace();
} finally{
httpResponse.close();
httpClient.close();
}
return responseData;
} /**
* get方法
* @param url
* @param params
* @param header
* @param connectTimeout
* @param readTimeout
* @return
* @throws IOException
*/
public static String doGet(String url, HttpParamers params, HttpHeader header, int connectTimeout, int readTimeout) throws IOException {
String responseData = "";
CloseableHttpClient httpClient = null;
CloseableHttpResponse httpResponse = null;
try{
String query = params.getQueryString(DEFAULT_CHARSET);
url = buildGetUrl(url, query);
HttpGet httpGet = new HttpGet(url);
setHeader(httpGet, header);
httpClient = HttpClients.createDefault();
httpResponse = httpClient.execute(httpGet);
HttpEntity resEntity = httpResponse.getEntity();
responseData = EntityUtils.toString(resEntity);
} catch (Exception e){
e.printStackTrace();
} finally{
httpResponse.close();
httpClient.close();
}
return responseData;
} private static void setHeader(HttpRequestBase httpRequestBase, HttpHeader header){
if(header != null){
Map<String,String> headerMap = header.getParams();
if (headerMap != null && !headerMap.isEmpty()) {
Set<Map.Entry<String, String>> entries = headerMap.entrySet();
for (Map.Entry<String, String> entry : entries) {
String name = entry.getKey();
String value = entry.getValue();
httpRequestBase.setHeader(name, value);
}
}
}
} private static String buildGetUrl(String url, String query) throws IOException {
if (query == null || query.equals("")) {
return url;
}
StringBuilder newUrl = new StringBuilder(url);
boolean hasQuery = url.contains("?");
boolean hasPrepend = (url.endsWith("?")) || (url.endsWith("&"));
if (!hasPrepend) {
if (hasQuery) {
newUrl.append("&");
} else {
newUrl.append("?");
hasQuery = true;
}
}
newUrl.append(query);
hasPrepend = false;
return newUrl.toString();
}
}
HttpService.java
package demo; import java.util.Map; import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference; public class HttpService {
private String serverUrl;
private int connectTimeout = 15000;
private int readTimeout = 30000;
public HttpService(String serverUrl) {
this.serverUrl = serverUrl.trim();
}
public Map<String, Object> commonService(String serviceUrl, HttpParamers paramers) throws Exception{
return commonService(serviceUrl, paramers, null);
}
public Map<String, Object> commonService(String serviceUrl, HttpParamers paramers, HttpHeader header) throws Exception{
String response = service(serviceUrl, paramers, header);
try {
Map<String, Object> result = JSONObject.parseObject(response, new TypeReference<Map<String, Object>>() {});
if ((result == null) || (result.isEmpty())) {
throw new Exception("远程服务返回的数据无法解析");
}
Integer code = (Integer) result.get("code");
if ((code == null) || (code.intValue() != 0)) {
throw new Exception((String) result.get("message"));
}
return result;
} catch (Exception e) {
throw new Exception("返回结果异常,response:" + response, e);
}
}
public String service(String serviceUrl, HttpParamers paramers) throws Exception {
return service(serviceUrl, paramers, null);
}
public String service(String serviceUrl, HttpParamers paramers, HttpHeader header) throws Exception {
String url = this.serverUrl + serviceUrl;
String responseData = "";
try {
responseData = HttpClient.doService(url, paramers, header, this.connectTimeout, this.readTimeout);
} catch (Exception e) {
throw new Exception(e.getMessage(), e);
}
return responseData;
} public String getServerUrl() {
return this.serverUrl;
} public int getConnectTimeout() {
return this.connectTimeout;
} public int getReadTimeout() {
return this.readTimeout;
} public void setConnectTimeout(int connectTimeout) {
this.connectTimeout = connectTimeout;
} public void setReadTimeout(int readTimeout) {
this.readTimeout = readTimeout;
}
}
测试例子Test1.java
package demo; import org.junit.Ignore;
import org.junit.Test; public class Test1 { //免费的在线REST服务, 提供测试用的HTTP请求假数据
//接口信息说明可见:http://www.hangge.com/blog/cache/detail_2020.html
String uri = "http://jsonplaceholder.typicode.com"; //get方式请求数据
//请求地址:http://jsonplaceholder.typicode.com/posts
@Ignore("暂时忽略")
@Test
public void test1() {
System.out.print("\n" + "test1---------------------------"+ "\n");
HttpParamers paramers = HttpParamers.httpGetParamers();
String response = "";
try {
HttpService httpService = new HttpService(uri);
response = httpService.service("/posts", paramers);
} catch (Exception e) {
e.printStackTrace();
}
System.out.print(response);
} //get方式请求数据
//请求地址:http://jsonplaceholder.typicode.com/posts?userId=5
@Ignore("暂时忽略")
@Test
public void test2() {
System.out.print("\n" + "test2---------------------------"+ "\n");
HttpParamers paramers = HttpParamers.httpGetParamers();
paramers.addParam("userId", "5");
String response = "";
try {
HttpService httpService = new HttpService(uri);
response = httpService.service("/posts", paramers);
} catch (Exception e) {
e.printStackTrace();
}
System.out.print(response);
} //post方式请求数据
//请求地址:http://jsonplaceholder.typicode.com/posts
@Test
public void test3() {
System.out.print("\n" + "test3---------------------------"+ "\n");
HttpParamers paramers = HttpParamers.httpPostParamers();
paramers.addParam("time", String.valueOf(System.currentTimeMillis()));
String response = "";
try {
HttpService httpService = new HttpService(uri);
response = httpService.service("/posts", paramers);
} catch (Exception e) {
e.printStackTrace();
}
System.out.print(response);
}
}
一个java的http请求的封装工具类的更多相关文章
- JAVA之旅(五)——this,static,关键字,main函数,封装工具类,生成javadoc说明书,静态代码块
JAVA之旅(五)--this,static,关键字,main函数,封装工具类,生成javadoc说明书,静态代码块 周末收获颇多,继续学习 一.this关键字 用于区分局部变量和成员变量同名的情况 ...
- 泛型(二)封装工具类CommonUtils-把一个Map转换成指定类型的javabean对象
1.commons-beanutils的使用 commons-beanutils-1.9.3.jar 依赖 commons-logging-1.2.jar 代码1: String className ...
- Android OkHttp网络连接封装工具类
package com.lidong.demo.utils; import android.os.Handler; import android.os.Looper; import com.googl ...
- MySQL JDBC常用知识,封装工具类,时区问题配置,SQL注入问题
JDBC JDBC介绍 Sun公司为了简化开发人员的(对数据库的统一)操作,提供了(Java操作数据库的)规范,俗称JDBC,这些规范的由具体由具体的厂商去做 对于开发人员来说,我们只需要掌握JDBC ...
- Http请求通信(工具类)
Http请求通信(工具类) 异步消息处理流程是: 首先需要在主线程当中创建一个Handle对象,并重写handlerMessage()方法. 然后当子线程中需要进行UI操作时,就创建一个Message ...
- Java判断不为空的工具类总结
1.Java判断是否为空的工具类,可以直接使用.包含,String字符串,数组,集合等等. package com.bie.util; import java.util.Collection; imp ...
- Java字符串转16 进制工具类Hex.java
Java字符串转16 进制工具类Hex.java 学习了:https://blog.csdn.net/jia635/article/details/56678086 package com.strin ...
- Java中的AES加解密工具类:AESUtils
本人手写已测试,大家可以参考使用 package com.mirana.frame.utils.encrypt; import com.mirana.frame.constants.SysConsta ...
- 一个.java源文件中可以有多个类吗?(内部类除外)有什么条件?
一个.java源文件中可以有多个类吗?(内部类除外)有什么条件?带着这个疑惑,动手建几个测试类, 揭开心中的疑惑.以下是解开疑惑过程: package test;/** * 一个.java源文件中可以 ...
随机推荐
- Python迭代器(函数名的应用,新版格式化输出)
1. 函数名的运用 你们说一下,按照你们的理解,函数名是什么? 函数名的定义和变量的定义几乎一致,在变量的角度,函数名其实就是一个变量,具有变量的功能:可以赋值:但是作为函数名他也有特殊的功能 ...
- 微信小程序 wxml 文件中如何让多余文本省略号显示?
废话不多说,之前写小程序碰到了一个问题,如何在 wxml 页面中截取数据? 1.wxs 取数据想必大家都会,不就是 substring 吗?但是这种方法在 wxml 页面中是无效的. 那还有 cs ...
- 【机器学习之数学】03 有约束的非线性优化问题——拉格朗日乘子法、KKT条件、投影法
目录 1 将有约束问题转化为无约束问题 1.1 拉格朗日法 1.1.1 KKT条件 1.1.2 拉格朗日法更新方程 1.1.3 凸优化问题下的拉格朗日法 1.2 罚函数法 2 对梯度算法进行修改,使其 ...
- SPA项目开发之首页导航左侧菜单栏
1. Mock.js 前后端分离开发开发过程当中,经常会遇到以下几个尴尬的场景: 1. 老大,接口文档还没输出,我的好多活干不下去啊! 2. 后端小哥,接口写好了没,我要测试啊! 前后端分离之后,前端 ...
- Python机器学习笔记——One Class SVM
前言 最近老板有一个需求,做单样本检测,也就是说只有一个类别的数据集与标签,因为在工厂设备中,控制系统的任务是判断是是否有意外情况出现,例如产品质量过低,机器产生奇怪的震动或者机器零件脱落等.相对来说 ...
- deepin系统右键刷新-解决增删改文件没有变化
deepin 新建/删除/修改-->文件/文件夹后 目录不刷新解决方案 方法1: F5键刷新 方法2: 通过修改配置文件-->调整最大文件监控数量(建议使用这种方式) sudo vim / ...
- acwing 528. 奶酪 解题记录
习题地址 https://www.acwing.com/problem/content/description/530/ 现有一块大奶酪,它的高度为h,它的长度和宽度我们可以认为是无限大的,奶酪中间有 ...
- C#开发BIMFACE系列28 服务端API之获取模型数据13:获取三维视点或二维视图列表
系列目录 [已更新最新开发文章,点击查看详细] 本篇主要介绍如何获取一个模型中包含的三维视点或二维视图列表. 请求地址:GET https://api.bimface.com/data/v2/ ...
- golang数据结构之单链表
实现单链表的增删查改. 目录如下: singleLink.go package link import ( "fmt" ) //HeroNode 链表节点 type HeroNod ...
- 一文学会 TypeScript 的 82% 常用知识点(下)
一文学会 TypeScript 的 82% 常用知识点(下) 前端专栏 2019-11-23 18:39:08 都已经 9021 年了,TypeScript(以下简称 TS)作为前端工程师不得 ...