1:首先pom.xml文件引进一个依赖,okhttp(用了几个方式,发现这个很好用)
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.12.1</version>
</dependency>
2:其次就是开始使用里面方法进行调用接口了
String newurl ="http://你要调用的url"
//这里需要传json类型数据
JSONObject jo = new JSONObject();
jo.put("xxx","xxxx");
OkHttpClient client = new OkHttpClient().newBuilder()
.sslSocketFactory(createInsecureSocketFactory(), new TrustAllCerts())
.hostnameVerifier((hostname, session) -> true)
.build();
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(JSON, jo.toString());
Request request = new Request.Builder()
.url(newurl)
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
String res = response.body().string();
System.out.println(res);
return res;
}
然后就ok了,如果调用接口的比较多,可以将这串代码封装为一个带有两个参数(数据,url)的方法就行了