Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit 2.0 beta1: how to post raw String body

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.

like image 239
Vitaliy Istomov Avatar asked Sep 18 '15 15:09

Vitaliy Istomov


Video Answer


1 Answers

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) {
    // ...
}
like image 150
Wasky Avatar answered Oct 17 '22 02:10

Wasky