java使用okhttp3调用接口
- 首先导入依赖
// 我用的是springboot2.1.x版本,不同版本可以自己去选择
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.14.9</version>
</dependency>
// 由于我还使用了hutool工具包,自己可以看情况使用
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.12</version>
</dependency>
- 使用okhtp调用get请求接口
public String get(String url, Map<String, String> params, String token) {
OkHttpClient client = new OkHttpClient();
HttpUrl.Builder query = HttpUrl.get(url).newBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
query.addQueryParameter(entry.getKey(), entry.getValue());
}
Request.Builder builder = new Request.Builder().url(query.build());
if (StrUtil.isNotEmpty(token)) {
builder.addHeader("token", token);
}
try {
Response response = client.newCall(builder.build()).execute();
ResponseBody body = response.body();
return body == null ? null : body.string();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
- 使用okhtp调用post请求接口(formdata)
public String postFormBody(String url, Map<String, String> params, String token, Map<String, String> headParam) {
OkHttpClient client = new OkHttpClient();
FormBody.Builder builder = new FormBody.Builder();
for (Map.Entry<String, String> entry : params.entrySet()) {
builder.add(entry.getKey(), entry.getValue());
}
Request.Builder requestBuilder = new Request.Builder()
.url(url)
.post(builder.build());
if (StrUtil.isNotEmpty(token)) {
requestBuilder.addHeader("token", token);
}
if (!CollectionUtils.isEmpty(headParam)) {
for (Map.Entry<String, String> entry : headParam.entrySet()) {
requestBuilder.addHeader(entry.getKey(), entry.getValue());
}
}
try {
Response response = client.newCall(requestBuilder.build()).execute();
ResponseBody body = response.body();
return body == null ? null : body.string();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
- 使用okhtp调用post请求接口(json)
public String postJsonBody(String url, Map<String, String> params) {
OkHttpClient client = new OkHttpClient();
JSONObject jsonObject = new JSONObject();
for (Map.Entry<String, String> entry : params.entrySet()) {
jsonObject.put(entry.getKey(), entry.getValue());
}
RequestBody requestBody = RequestBody.create(
MediaType.parse(org.springframework.http.MediaType.APPLICATION_JSON_VALUE),
jsonObject.toString()
);
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
try {
Response response = client.newCall(request).execute();
ResponseBody body = response.body();
return body == null ? null : body.string();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}