工具类:OkHttpClients
import com.alibaba.fastjson.JSON;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
/**
* Created by zhonglin on 2018/7/25.
*/
public class OkHttpClients {
/**
* get请求
*/
public static OkhttpResult get(OkHttpParam restParam, Class tClass) throws Exception {
String url = restParam.getApiUrl();
if (restParam.getApiPath() != null) {
url = url+restParam.getApiPath();
}
Request request = new Request.Builder()
.url(url)
.get()
.build();
return exec(restParam, request, tClass);
}
/**
* POST请求json数据
*/
public static OkhttpResult post(OkHttpParam restParam, String reqJsonData, Class tClass) throws Exception {
String url = restParam.getApiUrl();
if (restParam.getApiPath() != null) {
url = url+restParam.getApiPath();
}
RequestBody body = RequestBody.create(restParam.getMediaType(), reqJsonData);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
return exec(restParam, request, tClass);
}
/**
* POST请求map数据
*/
public static OkhttpResult post(OkHttpParam restParam, Map parms, Class tClass) throws Exception {
String url = restParam.getApiUrl();
if (restParam.getApiPath() != null) {
url = url+restParam.getApiPath();
}
FormBody.Builder builder = new FormBody.Builder();
if (parms != null) {
for (Map.Entry entry : parms.entrySet()) {
builder.add(entry.getKey(), entry.getValue());
}
}
FormBody body = builder.build();
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
return exec(restParam, request, tClass);
}
/**
* 返回值封装成对象
*/
private static OkhttpResult exec(
OkHttpParam restParam,
Request request,
Class tClass) throws Exception {
OkhttpResult clientResult = exec(restParam, request);
String result = clientResult.getResult();
int status = clientResult.getStatus();
T t = null;
if (status == 200) {
if (result != null && "".equalsIgnoreCase(result)) {
t = JSON.parseObject(result, tClass);
}
} else {
try {
result = JSON.parseObject(result, String.class);
} catch (Exception ex) {
ex.printStackTrace();
}
}
return new OkhttpResult<>(clientResult.getStatus(), result, t);
}
/**
* 执行方法
*/
private static OkhttpResult exec(
OkHttpParam restParam,
Request request) throws Exception {
OkhttpResult result = null;
okhttp3.OkHttpClient client = null;
ResponseBody responseBody = null;
try {
client = new okhttp3.OkHttpClient();
client.newBuilder()
.connectTimeout(restParam.getConnectTimeout(), TimeUnit.MILLISECONDS)
.readTimeout(restParam.getReadTimeout(), TimeUnit.MILLISECONDS)
.writeTimeout(restParam.getWriteTimeout(), TimeUnit.MILLISECONDS);
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
responseBody = response.body();
if (responseBody != null) {
String responseString = responseBody.string();
result = new OkhttpResult<>(response.code(), responseString, null);
}
} else {
throw new Exception(response.message());
}
} catch (Exception ex) {
throw new Exception(ex.getMessage());
} finally {
if (responseBody != null) {
responseBody.close();
}
if (client != null) {
client.dispatcher().executorService().shutdown(); //清除并关闭线程池
client.connectionPool().evictAll(); //清除并关闭连接池
try {
if (client.cache() != null) {
client.cache().close(); //清除cache
}
} catch (IOException e) {
throw new Exception(e.getMessage());
}
}
}
return result;
}
}
请求对象:OkHttpParam
import okhttp3.MediaType;
/**
* Created by zhonglin on 2018/7/25.
*/
public class OkHttpParam {
public static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");
/**
* 接口URL
*/
private String apiUrl;
/**
* 接口路径
*/
private String apiPath;
/**
* 读取超时时间
*/
private int readTimeout = 30 * 1000;
/**
* 写入超时时间
*/
private int writeTimeout = 30 * 1000;
/**
* 连接超时时间
*/
private int connectTimeout = 2 * 1000;
/**
* 编码类型
*/
private MediaType mediaType = MEDIA_TYPE_JSON;
public String getApiUrl() {
return apiUrl;
}
public void setApiUrl(String apiUrl) {
this.apiUrl = apiUrl;
}
public String getApiPath() {
return apiPath;
}
public void setApiPath(String apiPath) {
this.apiPath = apiPath;
}
public int getReadTimeout() {
return readTimeout;
}
public void setReadTimeout(int readTimeout) {
this.readTimeout = readTimeout;
}
public int getWriteTimeout() {
return writeTimeout;
}
public void setWriteTimeout(int writeTimeout) {
this.writeTimeout = writeTimeout;
}
public int getConnectTimeout() {
return connectTimeout;
}
public void setConnectTimeout(int connectTimeout) {
this.connectTimeout = connectTimeout;
}
public MediaType getMediaType() {
return mediaType;
}
public void setMediaType(MediaType mediaType) {
this.mediaType = mediaType;
}
}
响应对象:OkhttpResult
public class OkhttpResult {
private int status;
private String result;
private T resultObject;
public OkhttpResult() {
}
public OkhttpResult(int status, String result, T resultObject) {
this.status = status;
this.result = result;
this.resultObject = resultObject;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public T getResultObject() {
return resultObject;
}
public void setResultObject(T resultObject) {
this.resultObject = resultObject;
}
测试方法:
public class OkHttpClientsTest {
public static void main(String[] args) throws Exception {
OkHttpParam param = new OkHttpParam();
param.setApiUrl("http://127.0.0.1:7015/api");
param.setApiPath("/batch/btb_batchinfo");
Map map = new HashMap<>();
String a = "{\"body\":{\"batch_list\":[{\"batch_code\":\"3934630\",\"box_list\":[{\"box_code\":\"3934630201807*07\",\"qty\":1,\"sku\":\"6508827101\"},{\"box_code\":\"3934630201807*07\",\"qty\":1,\"sku\":\"S970000901\"},{\"box_code\":\"3934630201807*08\",\"qty\":1,\"sku\":\"6508827101\"}],\"from_warehouse\":\"218\",\"to_warehouse\":\"1321\"}]},\"header\":{\"message_id\":\"2018080114182503500949856842\",\"sign\":\"d21caa4cad66de334fafdcfa7b345bff\",\"time_stamp\":\"1533104305350\",\"transaction_type\":\"btb_batchinfo\"}}";
map.put("msg", JSON.toJSONString(a));
OkhttpResult result = OkHttpClients.post(param, map, String.class);
System.out.println("result:"+JSON.toJSONString(result));
}
}