模拟表单提交post请求

 pom配置:

<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.14.2</version>
</dependency>

 

后端代码:

/**
* 模拟表单提交
* @return
* @throws Exception
*/
public static String doPost_ok(String url,String requestData) throws Exception {
  String strResult = "";
  OkHttpClient client = new OkHttpClient().newBuilder().build();
  MediaType mediaType = MediaType.parse("application/json");
  RequestBody body = RequestBody.create(mediaType, requestData);
  Request request = new Request.Builder()
  .url(url)
  .method("POST", body)
  .addHeader("Content-Type", "application/json")
  .build();
  Response response = client.newCall(request).execute();
  int code = response.code();
if(code==200){
  strResult = response.body().string();
}
  return strResult;
}
posted @ 2022-08-11 14:26  亦寒yihan丶  阅读(139)  评论(0)    收藏  举报