原生OKHttp的Get和Post请求思路
<!--接收OKHttp返回json信息依赖-->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.3</version>
</dependency>
引入OkClientUtils工具类
package com.ruoyi.system.service.impl.msimpl.Wm;
import okhttp3.*;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
public class OkClientUtils {
/**
* get请求
* @param url
* @return
*/
public static String httpGet(String url) {
String result = null;
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
try {
Response response = client.newCall(request).execute();
result = response.body().string();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* post请求
* @param url
* @param data 提交的参数为key=value&key1=value1的形式
*/
public static String httpPost(String url, String data) {
String result = null;
OkHttpClient httpClient = new OkHttpClient.Builder()
.connectTimeout(60,TimeUnit.SECONDS)
.readTimeout(60,TimeUnit.SECONDS)
.writeTimeout(60,TimeUnit.SECONDS).build();
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), data);
Request request = new Request.Builder().url(url).post(requestBody).build();
try {
Response response = httpClient.newCall(request).execute();
result = response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
传入数据和路径,调用方法
package com.ruoyi.system.service.impl.msimpl.Wm;
import java.math.BigDecimal;
public class ClientData {
String field0002 = "wmOrder.getInfData().getField0002()";
String field0007 = "wmOrder.getInfData().getField0007()";
BigDecimal field0008 = null;
String jsonData = "{\n" +
" \"context\": {\n" +
" \"cultureName\": \"zh-CN\",\n" +
" \"orgCode\": \"U9组织.编码\",\n" +
" \"userCode\": \"U9用户编码\",\n" +
" \"entCode\": \"U9企业代码\"\n" +
" },\n" +
" \"infCode\": \"completeRpt.create\",\n" +
" \"infData\": {\n" +
" \"field0007\": \""+field0007+"\",\n" +
" \"field0008\": \""+field0008+"\",\n" +
" \"field0002\": \""+field0002+"\",\n" +
" }\n" +
"}";
String path="http://192.168.1.242/U9/RestServices/BL.IMES2U9SV.svc/Do";
//返回 成功或失败的json信息 ,用实体类进行解析
String postCheck = OkClientUtils.httpPost(path , jsonData);
}