1、Json、String、Map相互转换工具类
Mave依赖
com.squareup.okhttp3
okhttp
provided
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Jackson 工具类
* Title: MapperUtils
* Description:
*
* @author linke
* @version 1.0.0
* @date 2018/3/4 21:50
*/
public class MapperUtils {
private final static ObjectMapper objectMapper = new ObjectMapper();
public static ObjectMapper getInstance() {
return objectMapper;
}
/**
* 转换为 JSON 字符串
*
* @param obj
* @return
* @throws Exception
*/
public static String obj2json(Object obj) throws Exception {
return objectMapper.writeValueAsString(obj);
}
/**
* 转换为 JSON 字符串,忽略空值
*
* @param obj
* @return
* @throws Exception
*/
public static String obj2jsonIgnoreNull(Object obj) throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return mapper.writeValueAsString(obj);
}
/**
* 转换为 JavaBean
*
* @param jsonString
* @param clazz
* @return
* @throws Exception
*/
public static T json2pojo(String jsonString, Class clazz) throws Exception {
objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
return objectMapper.readValue(jsonString, clazz);
}
/**
* 字符串转换为 Map
*
* @param jsonString
* @return
* @throws Exception
*/
public static Map json2map(String jsonString) throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return mapper.readValue(jsonString, Map.class);
}
/**
* 字符串转换为 Map
*/
public static Map json2map(String jsonString, Class clazz) throws Exception {
Map> map = objectMapper.readValue(jsonString, new TypeReference
2、Http请求-OkHttp工具类
Maven依赖:
com.fasterxml.jackson.core
jackson-databind
provided
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* OKHttp3
*
* Description:
*
*
* @author linke
* @version v1.0.0
* @date 2019-07-29 14:05:08
* @see com.lingkang.myshop.plus.commons.utils
*/
public class OkHttpClientUtil {
private static final int READ_TIMEOUT = 100;
private static final int CONNECT_TIMEOUT = 60;
private static final int WRITE_TIMEOUT = 60;
private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
private static final byte[] LOCKER = new byte[0];
private static OkHttpClientUtil mInstance;
private OkHttpClient okHttpClient;
private OkHttpClientUtil() {
okhttp3.OkHttpClient.Builder clientBuilder = new okhttp3.OkHttpClient.Builder();
// 读取超时
clientBuilder.readTimeout(READ_TIMEOUT, TimeUnit.SECONDS);
// 连接超时
clientBuilder.connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS);
//写入超时
clientBuilder.writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS);
okHttpClient = clientBuilder.build();
}
/**
* 单例模式获取 NetUtils
*
* @return {@link OkHttpClientUtil}
*/
public static OkHttpClientUtil getInstance() {
if (mInstance == null) {
synchronized (LOCKER) {
if (mInstance == null) {
mInstance = new OkHttpClientUtil();
}
}
}
return mInstance;
}
/**
* GET,同步方式,获取网络数据
*
* @param url 请求地址
* @return {@link Response}
*/
public Response getData(String url) {
// 构造 Request
Request.Builder builder = new Request.Builder();
Request request = builder.get().url(url).build();
// 将 Request 封装为 Call
Call call = okHttpClient.newCall(request);
// 执行 Call,得到 Response
Response response = null;
try {
response = call.execute();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
/**
* POST 请求,同步方式,提交数据
*
* @param url 请求地址
* @param bodyParams 请求参数
* @return {@link Response}
*/
public Response postData(String url, Map bodyParams) {
// 构造 RequestBody
RequestBody body = setRequestBody(bodyParams);
// 构造 Request
Request.Builder requestBuilder = new Request.Builder();
Request request = requestBuilder.post(body).url(url).build();
// 将 Request 封装为 Call
Call call = okHttpClient.newCall(request);
// 执行 Call,得到 Response
Response response = null;
try {
response = call.execute();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
/**
* GET 请求,异步方式,获取网络数据
*
* @param url 请求地址
* @param myNetCall 回调函数
*/
public void getDataAsync(String url, final MyNetCall myNetCall) {
// 构造 Request
Request.Builder builder = new Request.Builder();
Request request = builder.get().url(url).build();
// 将 Request 封装为 Call
Call call = okHttpClient.newCall(request);
// 执行 Call
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
myNetCall.failed(call, e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
myNetCall.success(call, response);
}
});
}
/**
* POST 请求,异步方式,提交数据
*
* @param url 请求地址
* @param bodyParams 请求参数
* @param myNetCall 回调函数
*/
public void postDataAsync(String url, Map bodyParams, final MyNetCall myNetCall) {
// 构造 RequestBody
RequestBody body = setRequestBody(bodyParams);
// 构造 Request
buildRequest(url, myNetCall, body);
}
/**
* 同步 POST 请求,使用 JSON 格式作为参数
*
* @param url 请求地址
* @param json JSON 格式参数
* @return 响应结果
* @throws IOException 异常
*/
public String postJson(String url, String json) throws IOException {
RequestBody body = RequestBody.create(json, JSON);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = okHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
} else {
throw new IOException("Unexpected code " + response);
}
}
/**
* 异步 POST 请求,使用 JSON 格式作为参数
*
* @param url 请求地址
* @param json JSON 格式参数
* @param myNetCall 回调函数
* @throws IOException 异常
*/
public void postJsonAsync(String url, String json, final MyNetCall myNetCall) throws IOException {
RequestBody body = RequestBody.create(json, JSON);
// 构造 Request
buildRequest(url, myNetCall, body);
}
/**
* 构造 POST 请求参数
*
* @param bodyParams 请求参数
* @return {@link RequestBody}
*/
private RequestBody setRequestBody(Map bodyParams) {
RequestBody body = null;
okhttp3.FormBody.Builder formEncodingBuilder = new okhttp3.FormBody.Builder();
if (bodyParams != null) {
Iterator iterator = bodyParams.keySet().iterator();
String key = "";
while (iterator.hasNext()) {
key = iterator.next().toString();
formEncodingBuilder.add(key, bodyParams.get(key));
}
}
body = formEncodingBuilder.build();
return body;
}
/**
* 构造 Request 发起异步请求
*
* @param url 请求地址
* @param myNetCall 回调函数
* @param body {@link RequestBody}
*/
private void buildRequest(String url, MyNetCall myNetCall, RequestBody body) {
Request.Builder requestBuilder = new Request.Builder();
Request request = requestBuilder.post(body).url(url).build();
// 将 Request 封装为 Call
Call call = okHttpClient.newCall(request);
// 执行 Call
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
myNetCall.failed(call, e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
myNetCall.success(call, response);
}
});
}
/**
* 自定义网络回调接口
*/
public interface MyNetCall {
/**
* 请求成功的回调处理
*
* @param call {@link Call}
* @param response {@link Response}
* @throws IOException 异常
*/
void success(Call call, Response response) throws IOException;
/**
* 请求失败的回调处理
*
* @param call {@link Call}
* @param e 异常
*/
void failed(Call call, IOException e);
}
}
3、微服务result工具类
通用数据传输对象
import lombok.Data;
import java.io.Serializable;
/**
* 通用数据传输对象
*
* Description:
*
*
* @author linke
* @version v1.0.0
* @date 2019-07-26 04:43:54
* @see com.lingkang.myshop.plus.commons.dto
*/
@Data
public class ResponseResult implements Serializable {
private static final long serialVersionUID = 3468352004150968551L;
/**
* 状态码
*/
private Integer code;
/**
* 消息
*/
private String message;
/**
* 返回对象
*/
private T data;
public ResponseResult() {
super();
}
public ResponseResult(Integer code) {
super();
this.code = code;
}
public ResponseResult(Integer code, String message) {
super();
this.code = code;
this.message = message;
}
public ResponseResult(Integer code, Throwable throwable) {
super();
this.code = code;
this.message = throwable.getMessage();
}
public ResponseResult(Integer code, T data) {
super();
this.code = code;
this.data = data;
}
public ResponseResult(Integer code, String message, T data) {
super();
this.code = code;
this.message = message;
this.data = data;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((data == null) ? 0 : data.hashCode());
result = prime * result + ((message == null) ? 0 : message.hashCode());
result = prime * result + ((code == null) ? 0 : code.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
ResponseResult> other = (ResponseResult>) obj;
if (data == null) {
if (other.data != null) {
return false;
}
} else if (!data.equals(other.data)) {
return false;
}
if (message == null) {
if (other.message != null) {
return false;
}
} else if (!message.equals(other.message)) {
return false;
}
if (code == null) {
if (other.code != null) {
return false;
}
} else if (!code.equals(other.code)) {
return false;
}
return true;
}
/**
* 通用状态码
*
* Description:
*
*
* @author Lusifer
* @version v1.0.0
* @date 2019-07-30 05:02:49
* @see com.funtl.myshop.plus.commons.dto
*/
public class CodeStatus {
/**
* 请求成功
*/
public static final int OK = 20000;
/**
* 请求失败
*/
public static final int FAIL = 20002;
/**
* 非法请求
*/
public static final int ILLEGAL_REQUEST = 50000;
/**
* 非法令牌
*/
public static final int ILLEGAL_TOKEN = 50008;
/**
* 其他客户登录
*/
public static final int OTHER_CLIENTS_LOGGED_IN = 50012;
/**
* 令牌已过期
*/
public static final int TOKEN_EXPIRED = 50014;
}
}