依赖包,用的是okhttp3
com.squareup.okhttp3 okhttp4.9.0
在将object转成json的时候,也用到了一个包
二、具体实现代码com.google.code.gson gson2.8.6
package com.example.autoapi.http.service;
import com.google.gson.Gson;
import okhttp3.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class HttpService {
// post json 无header方式
public String doPostJson(String url,Object data){
return doPostJson(url,null,data);
}
// post form 无header方式
public String doPostForm(String url,Map params){
return doPostForm(url,null,params);
}
public String doPostForm(String url,Map headers,Map params){
OkHttpClient client = new OkHttpClient();
FormBody.Builder builder= new FormBody.Builder();
for (Map.Entry entry:params.entrySet()){
builder.add(entry.getKey(), String.valueOf(entry.getValue()));
}
RequestBody requestBody = builder.build();
Request request = new Request.Builder()
.url(url)
.headers(Headers.of(headers==null?new HashMap<>():headers))
.post(requestBody)
.build();
Call call = client.newCall(request);
try {
Response response = call.execute();
String body = response.body().string();
return body;
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
public String doPostJson(String url, Map headers,Object data){
OkHttpClient client = new OkHttpClient();
// 1、构建请求
MediaType mediaType = MediaType.parse("application/json");
// Gson是json工具类,将x转成json
Gson gson = new Gson();
RequestBody requestBody = RequestBody.create(gson.toJson(data), mediaType);
Request request = new Request.Builder()
.url(url)
.headers(Headers.of(headers==null?new HashMap<>():headers))
.post(requestBody)
.build();
Call call = client.newCall(request);
try {
Response response = call.execute();
String body = response.body().string();
return body;
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
}
三、Json格式的请求讲解
整个请求的传参
public String doPostJson(String url, Mapheaders,Object data
url 字符串格式String
headers Map
data 是Object(本质上也是一个Map)
data{
"text": {
"content":"我就是我, @XXX 是不一样的烟火",
"name":"张三",
},
"msgtype":"text"
}
json 的传参:Object data
如上,整体其实也是一个Map,构造Objec data
1、Objec data
Mapdata = new HashMap<>();
2、data里面的entry,key=value,value的值,也是一个Map,所以data的类型是
Map
3、里面的value值也是一个map
Maptext = new HashMap<>();
整体的构造请求data
Maptext = new HashMap<>(); text.put("content",template); Map data = new HashMap<>(); data.put("msgtype","text"); data.put("text",text); String url= DING_ALARM_URL+token; HttpRequest httpRequest = HttpRequest.builder() .postJson() .url(url) .data(data) .build(); HttpFacade.doRequest(httpRequest); }
再构造请求的时候
MediaType mediaType = MediaType.parse("application/json");
// Gson是json工具类,将x转成json
Gson gson = new Gson();
RequestBody requestBody = RequestBody.create(gson.toJson(data), mediaType);
1、RequestBody 需要添加MediaTpye
2、这里将data转成了json格式
四、Form格式的请求讲解public String doPostForm(String url,Mapheaders,Map params)
headers是Map
params 是Map
构建builder的时候,需要用Map里的值给builder赋值。这里用了一个循环



