SpringBoot使用OkHttp

导入依赖:

<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.6.0</version>
</dependency>

调用POST方法:

MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
Request request = new Request.Builder()
.url(dataAddr)
.post(RequestBody.create(mediaType, reqJsonStr))
.build();
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
log.error("onFailure: {} ",e.getMessage());
}

@Override
public void onResponse(Call call, Response response) throws IOException {
//先使用String进行接收
String responseStr = response.body().string();
log.info("responseStr: "+responseStr);

JSONObject resJSONObject = JSON.parseObject(responseStr);
if (resJSONObject.get("code").equals(200)) {
JSONArray jsonArray = (JSONArray) resJSONObject.get("data");
//进行业务处理
}
}
});

-----------------------------------
SpringBoot使用OkHttp
https://blog.51cto.com/u_15127509/4378289

posted @ 2022-08-16 10:52  疯子110  阅读(1810)  评论(0编辑  收藏  举报