I am looking for some way to post request with raw body with new Retrofit 2.0b1. Something like this:
@POST("/token")
Observable<TokenResponse> getToken(@Body String body);
As far as I understand, there should be some kind of strait "to-string" converter, but it is not clear to me yet how it works.
There were ways to make it happen in 1.9 with TypedInput, but it does not help in 2.0 anymore.
In Retrofit 2 you can use RequestBody
and ResponseBody
to post a body to server using String
data and read from server's response body as String
.
First you need to declare a method in your RetrofitService:
interface RetrofitService {
@POST("path")
Call<ResponseBody> update(@Body RequestBody requestBody);
}
Next you need to create a RequestBody
and Call
object:
Retrofit retrofit = new Retrofit.Builder().baseUrl("http://somedomain.com").build();
RetrofitService retrofitService = retrofit.create(RetrofitService.class);
String strRequestBody = "body";
RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"),strRequestBody);
Call<ResponseBody> call = retrofitService.update(requestBody);
And finally make a request and read response body as String
:
try {
Response<ResponseBody> response = call.execute();
if (response.isSuccess()) {
String strResponseBody = response.body().string();
}
} catch (IOException e) {
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With