1、引入okhttp3依赖
<!-- okhttp -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
</dependency>
2、封装get、post请求工具
2-1、新建utils包,新建HttpUtil
package org.springblade.modules.system.utils;
import java.io.IOException;
import java.util.Map;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
public class HttpUtil {
private static OkHttpClient client = new OkHttpClient();
public static final MediaType JSON = MediaType.parse("application/json;charset=utf-8");
public static String getResponseWithParams(String url, Map<String, String> params) {
HttpUrl httpUrl = HttpUrl.parse(url);
HttpUrl.Builder builder = httpUrl.newBuilder();
if (params != null) {
for (String key : params.keySet()) {
builder.addQueryParameter(key, params.get(key));
}
}
Request request = new Request.Builder().url(builder.build()).build();
try {
String res = client.newCall(request).execute().body().string();
return res;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String getResponse(String url) {
Request request = new Request.Builder().url(url).build();
try {
String res = client.newCall(request).execute().body().string();
return res;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String postResponseWithParamsInMap(String url, Map<String, String> params, String headerKey,
String headerValue) {
FormBody.Builder builder = new FormBody.Builder();
if (params != null) {
for (String key : params.keySet()) {
builder.addEncoded(key, params.get(key));
}
}
RequestBody body = builder.build();
Request request = new Request.Builder().url(url).addHeader("Content-Type", "application/json;charset=UTF-8")
.post(body).build();
try {
String res = client.newCall(request).execute().body().string();
return res;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String postResponseWithParamsInJson(String url, String json) {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder().url(url).post(body).build();
try {
String res = client.newCall(request).execute().body().string();
return res;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}