在常用的服务中会经常有调用外部API的需求,这时候就需要用到一些网络请求的工具类了。大部分工具都是基于okhttp的,这里简单进行封装
使用okhttp3+fastjson
引入依赖
com.squareup.okhttp3
okhttp
com.squareup.okio
okio-jvm
3.0.0
com.alibaba
fastjson
1.2.83
工具类代码
package com.example.platformservice.util;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.example.platformservice.threepart.entity.RestResponse;
import com.example.platformservice.threepart.dto.UserDTO;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import okhttp3.RequestBody;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* OkHttpClient封装
*/
@Slf4j
public class OkHttp3ClientManager {
private static OkHttp3ClientManager mInstance;
private OkHttpClient mOkHttpClient;
private OkHttp3ClientManager() {
mOkHttpClient = new OkHttpClient.Builder().readTimeout(30, TimeUnit.SECONDS) // 读取超时
.connectTimeout(10, TimeUnit.SECONDS) // 连接超时
.writeTimeout(60, TimeUnit.SECONDS) // 写入超时
.build();
}
public static OkHttp3ClientManager getInstance() {
if (mInstance == null) {
synchronized (OkHttp3ClientManager.class) {
if (mInstance == null) {
mInstance = new OkHttp3ClientManager();
}
}
}
return mInstance;
}
/**
* 构造get方法连接拼加参数
*
* @param mapParams
* @return
*/
private String buildUrlParams(Map mapParams) {
String strParams = "";
if (mapParams != null) {
Iterator iterator = mapParams.keySet().iterator();
String key = "";
while (iterator.hasNext()) {
key = iterator.next().toString();
strParams += "&" + key + "=" + mapParams.get(key);
}
}
return strParams;
}
/**
* 构造post请求参数-form形式
*
* @param bodyParamMap
* @return
*/
private RequestBody buildRequestBodyForm(Map bodyParamMap) {
RequestBody body = null;
// 创建请求的参数body
FormBody.Builder builder = new FormBody.Builder();
// 遍历key
if (null != bodyParamMap) {
for (Map.Entry entry : bodyParamMap.entrySet()) {
log.info("Key = " + entry.getKey() + ", Value = " + entry.getValue());
builder.add(entry.getKey(), entry.getValue());
}
}
body = builder.build();
return body;
}
/**
* 构造请求头
*
* @param headerMap
* @return
*/
private Headers buildHeaders(Map headerMap) {
Headers.Builder builder = new Headers.Builder();
// 构造header
// 遍历key
if (null != headerMap) {
for (Map.Entry entry : headerMap.entrySet()) {
log.info("Key = " + entry.getKey() + ", Value = " + entry.getValue());
builder.add(entry.getKey(), entry.getValue());
}
}
Headers build = builder.build();
return build;
}
/**
* HTTP接口-GET方式,返回为String
* 请求参数形式为params形式
*
* @param reqUrl 请求地址
* @param urlParamMap 请求参数map
* @return String 请求结果
*/
public String sendGet(String reqUrl, Map urlParamMap) throws IOException {
return sendGet(reqUrl, urlParamMap, null);
}
/**
* get请求
*
* @param reqUrl 请求地址
* @param urlParamMap 请求参数map
* @param headers 请求头map
* @return 请求结果
*/
public String sendGet(String reqUrl, Map urlParamMap, Map headers) throws IOException {
String UrlParams = buildUrlParams(urlParamMap);
String URL = reqUrl + "?" + UrlParams;
Request request = new Request.Builder()
.url(URL)
.headers(buildHeaders(headers))
.get()
.build();
Response response;
String result;
try {
response = mOkHttpClient.newCall(request).execute();
result = response.body().string();
} catch (IOException e) {
throw new IOException("DATA", e);
}
return result;
}
/**
* 表单形式post请求
*
* @param url 请求地址
* @param form post请求参数
* @return 请求结果
*/
public String sendPostForm(String url, Map form) throws IOException {
return sendPostForm(url, form, null);
}
/**
* 表单形式post请求
*
* @param url 请求地址
* @param form post请求参数
* @param headers 请求头
* @return String 请求结果
*/
public String sendPostForm(String url, Map form, Map headers) throws IOException {
RequestBody requestBody = buildRequestBodyForm(form);
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.headers(buildHeaders(headers))
.build();
Call call = mOkHttpClient.newCall(request);
//返回请求结果
try (Response response = call.execute()) {
return response.body().string();
} catch (IOException e) {
throw new IOException(e);
}
}
/**
* HTTP接口-POST方式,请求参数形式为body-json形式
* 不带header
*
* @param url
* @param jsonString
* @return String
*/
public String sendPostJson(String url, String jsonString) throws IOException {
return sendPostJson(url, jsonString, null);
}
/**
* HTTP接口-POST方式,请求参数形式为body-json形式
*
* @param url
* @param jsonString
* @param headers
* @return String
*/
public String sendPostJson(String url, String jsonString, Map headers) throws IOException {
RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonString);
Request request = new Request.Builder()
.post(body)
.headers(buildHeaders(headers))
.url(url)
.build();
Call call = mOkHttpClient.newCall(request);
//返回请求结果
try {
Response response = call.execute();
return response.body().string();
} catch (IOException e) {
throw new IOException(e);
}
}
/**
* HTTP接口-POST方式,请求参数形式为body-json形式
* 返回为bean 参数responseType 为 XXX.class
*
* @param url
* @param jsonString
* @param responseType
* @return
*/
public T sendPostJsonObject(String url, String jsonString, Class responseType) throws IOException {
String s = sendPostJson(url, jsonString);
if (s != null && !s.isEmpty()) {
T t = JSONObject.parseObject(s, responseType);
return t;
}
return null;
}
/**
* HTTP接口-POST方式,请求参数形式为body-json形式
* 返回为bean 为type 为 new TypeReference(){} 支持bean嵌套泛型
*
* @param url
* @param jsonString
* @param type
* @return String
*/
public T sendPostJsonObject(String url, String jsonString, TypeReference type) throws IOException {
String s = sendPostJson(url, jsonString);
if (s != null && !s.isEmpty()) {
T t = JSONObject.parseObject(s, type);
return t;
}
return null;
}
/**
* HTTP接口-POST方式,请求参数形式为body-json形式
* 返回为List 参数responseType 为 XXX.class
*
* @param url
* @param jsonString
* @param responseType
* @return String
*/
public List sendPostJsonList(String url, String jsonString, Class responseType) throws IOException {
String s = sendPostJson(url, jsonString);
if (s != null && !s.isEmpty()) {
List ts = JSONObject.parseArray(s, responseType);
return ts;
}
return null;
}
public static void main(String[] args) throws IOException {
String url = "http://localhost:8080/user/addUser";
UserDTO build = UserDTO.builder()
.username("user99")
.password("password2")
.build();
String jsonString = JSONObject.toJSONString(build);
RestResponse restResponse = OkHttp3ClientManager.getInstance().sendPostJsonObject(url, jsonString, new TypeReference>() {
});
log.info(restResponse.getResult() + "");
}
}
支持string返回和bean返回,支持泛型和嵌套bean