Example JDK is 1.8
1.7 and non-maven projects manually download okhttp, jar + okio.jar
1.pom.xml introduces dependencies
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.6.0</version>
</dependency>
2. Data reading uses net.jsonArray that comes with springBoot
import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;
3. Public code docking method
public static List<HashMap<String, Object>> httpPost(String url) {
try {
OkHttpClient client = new OkHttpClient();
String dataCenterToken = getDataCenterToken();
JSONObject json = new JSONObject(); //创建参数对象
json.put("username", username); //请求参数
json.put("token", dataCenterToken);//请求参数
System.out.println(dataCenterToken);
RequestBody body = RequestBody.create(MediaType.parse("application/json"), json.toJSONString()); //将请求参数对象传入
Request request = new Request.Builder()
.post(body) //请求方式 .post ; .get; .put; ...
.url(url) // 请求地址
.addHeader("Content-Type", "application/json")
.addHeader("Transfer-Encoding", "chunked")
.addHeader("Accept", "*/*")
.addHeader("Cache-Control", "no-cache")
.addHeader("Host", "sjzx.hebfda.gov.cn")
.addHeader("Accept-Encoding", "gzip, deflate")
.addHeader("Content-Length", "123")
.addHeader("Connection", "keep-alive")
.addHeader("cache-control", "no-cache")
.build();
JSONObject jsonObject = JSONObject.parseObject //开始请求
(client.newCall(request)
.execute()
.body()
.string());
if (jsonObject!=null && jsonObject.get("data")!=null) {
JSONArray jsonArray = JSONArray.fromObject(jsonObject.get("data")); //获取 net.sf.json JSONArray数据
List<HashMap<String,Object>> list = JSONArray.toList(jsonArray,new HashMap<String,String>(),new JsonConfig());//返回java.List数据
return list;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}