Categories
android post retrofit

Send Post Request with params using Retrofit

I’m 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 settings by 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 can’t 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’ve found the source of the problem. I’ve updated my retrofit code to receive List<LandingPageReport>. 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 api’s (webapi and wcf). All my other json response are arrays of objects. [{},{}] but in this call I’ve received this

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

But still I can’t manage to parse the response.

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