最近需要http调用一个服务,httpClient以前有使用,封装稍微繁琐一些;别人推荐使用Okhttp,自测一下,确实很方便。我简单测试一下get、post json格式的方法,废话不多讲,直接来代码。
package com.lkp;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
/**
* @author lkp
* DateTime:2020-08-26
*/
public class OkHttpTest {
private static Call.Factory client = null;
static {
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.retryOnConnectionFailure(true)
.connectTimeout(60, TimeUnit.SECONDS)
.followSslRedirects(true)
.readTimeout(60, TimeUnit.SECONDS)
.connectionPool(new ConnectionPool(200, 5, TimeUnit.MINUTES));
client = builder.build();
}
public static void main(String[] args) throws IOException {
OkhttpTest test = new OkhttpTest();
test.testGet();
test.testPostJSON();
}
public void testGet() throws IOException {
// 请求地址
String baseUrl = "url";
Request request = new Request.Builder().url(baseUrl).get().build();
System.out.println(execute(request));
}
public void testPostJSON() throws IOException {
// 请求地址
String baseUrl = "url";
JSONObject params = new JSONObject();
params.put("a", "5543");
RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8"), params.toJSONString());
Request request = new Request.Builder().url(baseUrl).post(requestBody).build();
System.out.println(execute(request));
}
private String execute(Request request) throws IOException {
try (Response response = client.newCall(request).execute()) {
if (response.isSuccessful()) {
return response.body().string();
} else {
throw new RuntimeException("远程调用异常");
}
} catch (IOException e) {
throw e;
}
}
}