添加依赖
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>5.0.0-alpha.11</version>
</dependency>
发送get请求
public static <T> T getRequest(String url, Map<String,String> params,Class<T> tClass){
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS).build();
HttpUrl.Builder httpBuilder = HttpUrl.parse(url).newBuilder();
if (params!=null){
params.forEach((k,v)->httpBuilder.addQueryParameter(k,v));
}
Request request = new Request.Builder()
.url(httpBuilder.build())
.get()
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.build();
try {
Response response = client.newCall(request).execute();
if (response.isSuccessful()){
System.out.println("响应结果:"+response.body().string());
return JSON.parseObject(response.body().string(),tClass);
}else {
throw new IOException("Unexpected code "+response);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
发送post请求,参数为json格式
public static <T> T postRequest(String url, Map<String,String> params,Class<T> tClass){
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS).build();
MediaType type = MediaType.parse("application/json;charset=utf-8");
JSONObject json = new JSONObject();
if (params!=null){
params.forEach((k,v)->json.put(k,v));
}
RequestBody requestBody = RequestBody.create(type, String.valueOf(json));
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.addHeader("Content-Type", "application/json;charset=utf-8")
.build();
try {
Response response = client.newCall(request).execute();
if (response.isSuccessful()){
System.out.println("响应结果:"+response.body().string());
return JSON.parseObject(response.body().string(),tClass);
}else {
throw new IOException("Unexpected code "+response);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}