Adam Adam - 1 month ago 14
Android Question

Send Post Request with params using Retrofit

am trying unsuccessfully to consume an API on Android using Retrofit library but while using POSTMAN i can see the expected results.

[POSTMAN SETTING]

*The api url (base+controller)

*HTTP Method set to POST

*Clicked the from-data or x-www-form-urlencoded

*Then i pass the two params on the key/value fields.

[ANDROID RETROFIT SETTING]

@POST("/GetDetailWithMonthWithCode")
void getLandingPageReport(@Query("code") String code,
@Query("monthact") String monthact,
Callback<LandingPageReport> cb);

@FormUrlEncoded
@POST("/GetDetailWithMonthWithCode")
void getLandingPageReport(@Field("code") String code,
@Field("monthact") String monthact,
Callback<LandingPageReport> cb);


None of this options works. But am getting {} as result.

[UPDATE]

Same setting using the standard HttpClient(and HttpPost) class works fine.

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);

List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("code", "testcode"));
urlParameters.add(new BasicNameValuePair("monthact", "feb-2015"));

post.setEntity(new UrlEncodedFormEntity(urlParameters));

HttpResponse response = client.execute(post);


Why i cant do this request and get the correct response in Retrofit?

[UPDATE 2]

@POST("/GetDetailWithMonthWithCode")
void getLandingPageReport(@Query("code") String code,
@Query("monthact") String monthact,
Callback<List<LandingPageReport>> cb);

@FormUrlEncoded
@POST("/GetDetailWithMonthWithCode")
void getLandingPageReport(@Field("code") String code,
@Field("monthact") String monthact,
Callback<List<LandingPageReport>>> cb);


After playing around i think i found the source of the problem. I ve update my retrofit code to receive List. But now this error occur

retrofit.RetrofitError: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

The reason is that i consume 2 apis (webapi and wcf). All my other jsons response are arrays of objects. [{},{}] but in this call i receive this

{
"GetDetailWithMonthWithCodeResult": [
{
"code": "test",
"field1": "test",
}
]
}


But still i cannot manage to parse the response.

Answer

I have found the solution. The issue was a problem in my classes structure. So i updated them like the following samples.

public class LandingPageReport {

    private ArrayList<LandingPageReportItem> GetDetailWithMonthWithCodeResult;

    // + Getter Setter methods
}

public class LandingPageReportItem {

    private String code;

    private String field1;

    // + Getter Setter methods
}

And then i use this retrofit configuration

@POST("/GetDetailWithMonthWithCode")
void getLandingPageReport(@Field("code") String code,
                          @Field("monthact") String monthact,
                          Callback<LandingPageReport> cb);
Comments