简体   繁体   中英

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. I am using okhttp3 with 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:

"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. 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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM