//使用Gson将对象转换为json字符串 String json = gson.toJson(book); //MediaType 设置Content-Type 标头中包含的媒体类型值 RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8") , json); Request request = new Request.Builder() .url("http://172.20.192.168...
综上所述,这是使用OkHttp3构造POST请求的body并发送请求的完整过程。确保你根据实际需求调整URL、请求头和请求体内容。
StringpostBodyJson="{\"name\":\"tony\",\"age\":18}"; // 构造参数 RequestBodyrequestBody=RequestBody.create(postBodyJson, JSON); Requestrequest=newRequest.Builder().url(url).header("token","123abc").post(requestBody).build(); OkHttpClientokHttpClient=newOkHttpClient(); Callcall=okHttp...
post请求创建request和get是一样的,只是post请求需要提交一个表单,就是RequestBody。表单的格式有好多种,普通的表单是: RequestBody body = new FormBody.Builder() .add("键", "值") .add("键", "值") ... .build(); RequestBody的数据格式都要指定Content-Type,常见的有三种: application/x-www-form...
.post(body) .build(); Response response; try { response = new OkHttpClient().newCall(requestOk).execute(); String jsonString = response.body().string(); if(response.isSuccessful()){ return jsonString; } } catch (Exception e) { ...
System.out.println(response.body().string()); } } }); post 请求 -- json格式提交 OkHttpClientokHttpClient=newOkHttpClient.Builder() .connectTimeout(10, TimeUnit.SECONDS) .writeTimeout(10, TimeUnit.SECONDS) .readTimeout(20, TimeUnit.SECONDS) ...
.post(body) .build(); Call call = okHttpClient.newCall(request); try { Response response = call.execute(); System.out.println(response.body().string()); } catch (IOException e) { e.printStackTrace(); } post请求创建request和get是一样的,只是post请求需要提交一个表单,就是RequestBody。表...
/*** HTTP接口-POST方式,请求参数形式为body-json形式** @param url* @param jsonString* @return String*/public static String sendPostWithJson(String url, String jsonString) throws IOException {OkHttpClient client = new OkHttpClient().newBuilder().build();RequestBody body = RequestBody.create(...
builder = new Request.Builder() .url(url) .post(requestBody); if (headers != null ...
为json字符串Stringjson=gson.toJson(book);//MediaType 设置Content-Type 标头中包含的媒体类型值RequestBodyrequestBody=FormBody.create(MediaType.parse("application/json; charset=utf-8"),json);Requestrequest=newRequest.Builder().url("http://172.20.192.168:8080/getbookByJson")//请求的url.post(...