max
max

Reputation: 6187

send two string item as body in retrofit

I have a retrofit object like this:

retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

and

@Headers
({
    "Content-Type: application/x-www-form-urlencoded",
            "cache-control: no-cache"
})
@POST("login")
Call<RegisterResponse> register(@Body String n1,@Body String n2);

which I know that is incorrect because of two body annotation.
so I have to use this code

@Headers
({
    "Content-Type: application/x-www-form-urlencoded",
            "cache-control: no-cache"
})
@POST("login")
Call<RegisterResponse> register(@Body TestObject testObject);

 class TestObject{
     String n1;
     String n2;

 }

but I have a server which I cannot change it and it get two parameters as body.
when I use postman my server works just fine and do what it should be done.
but when I use retrofit I got an error 500 "server internal error"
I have done this with okhttp

 HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
  interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
  OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();



  MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
  RequestBody body = RequestBody.create(mediaType, "n1=09369&n2=145616");
  Request request = new Request.Builder()
          .url(URL)
          .post(body)
          .addHeader("content-type", "application/x-www-form-urlencoded")
          .addHeader("cache-control", "no-cache")
          .addHeader("postman-token", "0761ac45-1fb7-78df-d088-2437ecb984a3")
          .build();

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

and its works fine but how can I do it with the retrofit?.

Upvotes: 0

Views: 1758

Answers (2)

Jameido
Jameido

Reputation: 1354

What you need is sending data with the @FormUrlEncoded annotation, read more about it here

You canuse it this way:

@FormUrlEncoded
@POST("login")
Call<RegisterResponse> register(@Field("n1") String n1, @Field("n2") String n2);

Upvotes: 1

Ashwani
Ashwani

Reputation: 1284

A bit of modification is required

class TestObject{
     @SerializedName("n1")
     @Expose
     String n1;//if your server is looking for key with name n1, or change it to the required key

     @SerializedName("n2")
     @Expose
     String n2;
 }

your call code will be same as it is.

hope this might be helpful.:)

Upvotes: 0

Related Questions