1

so I am trying to make a server request and the expected body for this request looks like this: ["1"]

but if I send a string as "[\"1\"]", I am getting an error

looking at the body, it's clear that I have to send a JSONArray , I tried achieving this using the following code:

JSONArray array = new JSONArray();
array.put("1");

but my body on stetho is shown as :

{
    "values":["1"]
}

maybe I am using a wrong class or something !

EDIT:

This is my api call with

OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .addNetworkInterceptor(new StethoInterceptor())
                    .build();

RetrofitService retrofitService2 =new Retrofit.Builder()
                    .baseUrl("http://blynk-cloud.com/")
                    .client(okHttpClient)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build()
                    .create(RetrofitService.class);

retrofitService2.closeDoor("3bf11f14e6094dd5a8f31f6d6fac8f3d",
                    "[\"1\"]")
                    .enqueue(new Callback<String>() {
                        @Override
                        public void onResponse(Call<String> call, Response<String> response) {
                           {

                            }

                        }

                        @Override
                        public void onFailure(Call<String> call, Throwable t) {

                        }
                    });

closeDoor method:

@PUT("/{id}/update/D12")
    Call<String> closeDoor(@Path("id") String id, @Body String code);

my stetho response : enter image description here

Abhishek Tiwari
  • 936
  • 10
  • 25

2 Answers2

1

If you want to send request JSON like this ["1"]

Change to :

    JsonArray array = new JsonArray();
    array.add(new JsonPrimitive("1"));
    //output ["1"]

Instead of:

    JSONArray array = new JSONArray();
    array.put("1");
Ramesh sambu
  • 3,577
  • 2
  • 24
  • 39
0

The reason you are getting a 500 error is that you are sending the response as text\plain as supposed to application\json which the server is expecting.

As suggested here, to send a raw JSON you need to use a RequestBody and pass it instead of String

RequestBody body = new RequestBody.create(MediaType.parse("application/json"),"[\"1\"]");

retrofitService2.closeDoor("3bf11f14e6094dd5a8f31f6d6fac8f3d",body).enqueue(...)

And change your retrofit method to

@PUT("/{id}/update/D12")
Call<String> closeDoor(@Path("id") String id, @Body RequestBody body);
Jobin Lawrance
  • 708
  • 1
  • 7
  • 11