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

Categories

0 votes
381 views
in Technique[技术] by (71.8m points)

java - 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.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...