Retrofit: Sending Post Request To Server In Android
I am using Retrofit to call APIs. I am sending a post request to API but in the callback I am getting empty JSON like this {}. Below is the code for RetrofitService @POST('/com/sea
Solution 1:
After waiting for the best response I thought of answering my own question. This is how I resolved my problem.
I changed the converter of RestAdapter of RetrofitService and created my own Converter. Below is my StringConverter
staticclassStringConverterimplementsConverter {
@Overridepublic Object fromBody(TypedInput typedInput, Type type)throws ConversionException {
Stringtext=null;
try {
text = fromStream(typedInput.in());
} catch (IOException ignored) {/*NOP*/ }
return text;
}
@Overridepublic TypedOutput toBody(Object o) {
returnnull;
}
publicstatic String fromStream(InputStream in)throws IOException {
BufferedReaderreader=newBufferedReader(newInputStreamReader(in));
StringBuilderout=newStringBuilder();
StringnewLine= System.getProperty("line.separator");
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
out.append(newLine);
}
return out.toString();
}
}
Then I set this converter to the RestAdapter in the Application class.
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(BASE_URL)
.setConverter(newStringConverter())
.build();
mRetrofitService = restAdapter.create(RetrofitService.class);
Now whenever I use Retrofit, I get the response in String. Then I converted that String JSONObject.
RetrofitService mRetrofitService = app.getRetrofitService();
mRetrofitService.getUser(user, newCallback<String>() {
@Overridepublicvoidsuccess(String result, Response arg1) {
System.out.println("success, result: " + result);
JSONObject jsonObject = newJSONObject(result);
}
@Overridepublicvoidfailure(RetrofitError error) {
System.out.println("failure, error: " + error);
}
});
Hence, I got the result in JSON form. Then I parsed this JSON as required.
Solution 2:
it may help you
JSONObject responseJsonObj = newJSONObject(responseString);
Post a Comment for "Retrofit: Sending Post Request To Server In Android"