1、get请求
public static JSONObject jsonGetRequest(String url, String username, String password) throws AppException {
OkHttpClient client = new OkHttpClient().newBuilder()
.connectTimeout(5, TimeUnit.SECONDS)
.writeTimeout(5, TimeUnit.MINUTES)
.readTimeout(5, TimeUnit.MINUTES)
.addInterceptor(new BasicAuthInterceptor(username, password)) //连接密码校验
.build();
Request req = new Request.Builder()
.url(url)
.get()
.build();
try (Response response = client.newCall(req).execute()) {
int status = response.code();
if (status != RESPONSE_STATUS_OK) {
throw new AppException("请求数据失败,服务错误,代码:" + status);
}
ResponseBody responseBody = response.body();
if(responseBody == null){
throw new AppException("请求数据失败,服务端返回数据类型不正确");
}
String content = responseBody.string();
if (StringUtils.isBlank(content)) {
throw new AppException("请求数据失败,服务端返回数据类型不正确");
}
JSONObject json = JSONObject.parseObject(content);
if (json == null) {
throw new AppException("请求数据失败,服务端返回数据类型不正确");
}
return json;
} catch (IOException e) {
log.error("okhttp3 post error >> ex = {}", e.getMessage());
throw new AppException("请求数据失败:" + e.getMessage());
}
}
2、post请求
private void post(String url, JSONObject postData) throws AppException{
OkHttpClient client = new OkHttpClient().newBuilder()
.connectTimeout(15, TimeUnit.SECONDS)
.writeTimeout(15, TimeUnit.SECONDS)
.readTimeout(15, TimeUnit.SECONDS)
.addInterceptor(new BasicAuthInterceptor(username, password));
.build();
MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(postData.toJSONString(), mediaType);
Request req = new Request.Builder()
.url(url)
.post(body)
.build();
try (Response response = client.newCall(req).execute()) {
int status = response.code();
if (status != RESPONSE_STATUS_OK) {
throw new AppException("请求数据失败,服务错误,代码:" + status);
}
ResponseBody responseBody = response.body();
if (responseBody == null) {
throw new AppException("请求数据失败,服务端返回数据类型不正确");
}
String content = responseBody.string();
log.info("response from sync data server, data: {}", content);
if (StringUtils.isBlank(content)) {
throw new AppException("请求数据失败,服务端返回数据类型不正确");
}
JSONObject json = JSONObject.parseObject(content);
if (json == null) {
throw new AppException("请求数据失败,服务端返回数据类型不正确");
}
if (0 != json.getInteger("error")) {
throw new AppException("请求数据失败," + json.getString("msg"));
}
} catch (IOException e) {
log.error("okhttp3 post error >> ex = {}", e.getMessage(), e);
throw new AppException("请求数据失败:" + e.getMessage());
}
}