Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
380 views
Welcome To Ask or Share your Answers For Others

1 Answer

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) {
    // ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...