0

Currently, I am using the below java code. Here, I am passing parameters in the url.

        RequestBody jsonRequestBody = RequestBody.create(mediaType, jsonBody.toString());             
        Request request = new Request.Builder()
                .url("http://x.x.x.x:8080/v1/m?identifier=" + identifier)
                .addHeader("claim", claim)
                .post(jsonRequestBody)
                .build();

        Response response = client.newCall(request).execute();`

The problem is that my spring boot api has '@RequestBody Class obj' and '@RequestParam identifier' as the parameters. As obj is the object of class 'Class', the passed request body will be automatically converted to the respective obj(implementing serializable). I don't want to pass query parameters in the request body; rather I want to pass it separately.

I am unable to pass post parameters as well as request body separately using OkHttp. I tried looking up various resources but no luck. Can anyone help me out with this?

Christian Baumann
  • 3,188
  • 3
  • 20
  • 37
  • The HTTP Get or Post methods do not stay open after a request. You have to make a second request for the remaining parameters you want to sent. Moreover you must use https instead of http, otherwise a sniffer can see your data very easily. – Dimitrios Ververidis Feb 09 '23 at 08:48
  • @DimitriosVerveridis I want to pass request parameters as well as request body in the same request. How can I achieve it? – ADUDODLA REDDY Feb 09 '23 at 09:50
  • I want to correct myself that HTTP Get or Post methods can leave the connection open and later replace the data with Put. However, this is not a good practice due to security issues, thus Put is rarely seen in implementations. – Dimitrios Ververidis Feb 09 '23 at 10:15
  • @DimitriosVerveridis I am sorry it is post actually. Thanks. – ADUDODLA REDDY Feb 09 '23 at 14:09

1 Answers1

0

Avoid using .put() method because it should be used when you want to replace something that you have already sent.

Instead use post method when you want to submit data for the first time:

.post(formBody)

where

RequestBody formBody = new FormBody.Builder()
        .add("message", "Your message")
        .build();

See here for details: https://stackoverflow.com/a/35135972/1244696

Dimitrios Ververidis
  • 1,118
  • 1
  • 9
  • 33