需要导入的依赖:
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.14.8</version>
</dependency>
1、发送POST请求代码
public static void post(){
//请求头参数head
Map<String,String> head = new HashMap();
head.put("head属性", "参数");
//请求体参数body
Map<String,Object> body = new HashMap();
body.put("body属性","body参数");
String url = "url路径";
JSONObject jsonObject = httpPost(head, body, url);
}
2、发送GET请求代码
public void get() {
//请求头参数
Map<String,String> params = new HashMap();
params.put("head属性", "请求头参数");
//查询参数
Map<String,Object> query = new HashMap();
query.put("query属性","我是参数");
String url = "url路径";
//get请求需要拼接查询参数,
String urlEnd = HttpUtil.getUrl(url, query);
JSONObject jsonObject = httpGet(params, urlEnd);
}
如果不需要传递head或者body这些参数,传递空的map就可以了
3、工具类代码
public class HttpUtil {
/**
* post请求TB
* @param head 请求头
* @param body 请求体
* @param url 请求路径
*/
@SneakyThrows
public static JSONObject httpPost(Map<String,String> head, Map<String,Object> body,String url){
//将body,键值对转换成JSON对象,如果访问调用的接口不需要JSON,可以使用如下add()添加键值对。
// RequestBody requestBody = new FormBody.Builder().add()
RequestBody requestBody =
RequestBody.create(MediaType.parse("application/json; charset=utf-8"),new JSONObject(body).toString());
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
Request request = new Request.Builder()
.url(url)
.headers(Headers.of(head))
.method("POST", requestBody)
.build();
Response response = client.newCall(request).execute();
JSONObject jsonObject = (JSONObject)JSONObject.parse(response.body().string());
return jsonObject;
}
/**
* get请求TB
* @param head 请求头
* @param url 请求路径
*/
@SneakyThrows
public static JSONObject httpGet(Map<String,String> head,String url){
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
Request request = new Request.Builder()
.url(url)
.headers(Headers.of(head))
.method("GET", null)
.build();
Response response = client.newCall(request).execute();
JSONObject jsonObject = (JSONObject)JSONObject.parse(response.body().string());
return jsonObject;
}
/**
*
* @param url 请求的接口地址
* @param params 入参map
* @return 如果是get请求,路径需要拼接查询参数,可通过如下方法拼接
*/
public static String getUrl(String url, Map<String, ?> params){
StringBuilder paramSplice = new StringBuilder();
paramSplice.append(url).append("?");
params.forEach((key, value) -> paramSplice.append(key).append("=").append(value).append("&"));
return paramSplice.toString();
}
}
调用连接请求超时问题:
OkHttpClient client = new OkHttpClient()
.newBuilder()
//设置超时时间
.connectTimeout(60000, TimeUnit.MILLISECONDS)
.readTimeout(60000, TimeUnit.MILLISECONDS)
.build();