使用okhttp发送put请求,并推送json参数。

直接上代码:

import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Test {
   
  public static void main(String[] args) throws Exception {
   
    String url = "http://****";
    String json = "{\"param\":\"value2\",\"key\":\"value\"}";
    OkHttpClient client = new OkHttpClient().newBuilder() //
        .readTimeout(60, TimeUnit.SECONDS) // 设置读取超时时间
        .writeTimeout(60, TimeUnit.SECONDS) // 设置写的超时时间
        .connectTimeout(60, TimeUnit.SECONDS) // 设置连接超时时间
        .build();

    MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    RequestBody body = RequestBody.create(json, JSON);
    Request request = new Request.Builder().url(url).put(body).build();
    try (Response response = client.newCall(request).execute()) {
   
      System.out.println(response.body().string());
    }
  }
}
04-13 21:04