这里使用JSON对象为参数,具体实现方法代码如下:
package cn.xlink.lift;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import java.io.IOException;
import java.util.Date;
import java.util.concurrent.TimeUnit;
//@Component
public class OKHttpConnection {
//http连接查询接口数据POST
public JSONObject httpPostConnect(String url,JSONObject jsonObject){
long startTime = new Date().getTime();
JSONObject resultForJson = null;
//设置媒体类型。application/json表示传递的是一个json格式的对象
MediaType mediaType = MediaType.parse("application/json;charset=UTF-8");
//创建okHttpClient对象
OkHttpClient okhttp = new OkHttpClient();
//设置okhttp超时
okhttp.newBuilder().connectTimeout(10000L, TimeUnit.MILLISECONDS).readTimeout(50000,TimeUnit.MILLISECONDS).build();
//创建RequestBody对象,将参数按照指定的MediaType封装
RequestBody requestBody = RequestBody.create(mediaType, jsonObject.toString());
//创建一个Request
Request