[英]How to use PUT request with okhttp3 in Java?
I'm very new to this so please be nice.我对此很陌生,所以请善待。 I am trying to make a PUT request to some endpoint in which I need to send that some boolean variable is true or false.
我正在尝试向某个端点发出 PUT 请求,在该端点中我需要发送一些 boolean 变量是真还是假。 I am using okhttp3 with Java 11.
我正在使用 okhttp3 和 Java 11。
final Request request = new Request.Builder()
.url(someBaseURL + "/" + obj.getKey() + "/path")
.build();
execute(request);
This is my code so far and I need to call the endpoint with the following URL:到目前为止,这是我的代码,我需要使用以下 URL 调用端点:
"someBaseURL/obj.key/path?booleanVariable=true"
“someBaseURL/obj.key/path?booleanVariable=true”
So my question is how do I make a PUT
request that adds this booleanVariable
with its value being true or false.所以我的问题是我如何发出一个
PUT
请求来添加这个booleanVariable
,其值为真或假。 I tried a very stupid and simple way just adding the "?booleanVariable=true"
to the .url()
but then that request is just a GET
and it doesn't work for me.我尝试了一种非常愚蠢和简单的方法,只是将
"?booleanVariable=true"
添加到.url()
但是那个请求只是一个GET
,它对我不起作用。
If you are sending data in body then you try this code:如果您在正文中发送数据,那么您可以尝试以下代码:
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\n\t\"first_param\":\"xxxxxx\"}");
Request request = new Request.Builder()
.url("http://localhost:8080/api-path?booleanVariable=true")
.put(body)
.addHeader("Content-Type", "application/json")
.build();
Response response = client.newCall(request).execute();
or if you only sending data in params then you should try below code或者如果您只在参数中发送数据,那么您应该尝试下面的代码
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\n\t\n}");
Request request = new Request.Builder()
.url("http://localhost:8080/api-path?booleanVariable=true")
.put(body)
.addHeader("Content-Type", "application/json")
.build();
Response response = client.newCall(request).execute();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.