Retrofit 2.0 beta1: how to post raw String body

后端 未结 2 1403
隐瞒了意图╮
隐瞒了意图╮ 2020-12-14 19:35

I am looking for some way to post request with raw body with new Retrofit 2.0b1. Something like this:

@POST(\"/token\")
Observable getT         


        
相关标签:
2条回答
  • 2020-12-14 20:01

    In Retrofit 2.0.0-beta2 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) {
        // ...
    }
    
    0 讨论(0)
  • 2020-12-14 20:05

    You should be registering a converter for your Type when you are building your Retrofit using addConverter(type, converter).

    Converter<T> in 2.0 uses similar approach using old Converter in 1.x version.

    Your StringConverter should be something like this:

    public class StringConverter implements Converter<Object>{
    
    
        @Override
        public String fromBody(ResponseBody body) throws IOException {
            return ByteString.read(body.byteStream(), (int) body.contentLength()).utf8();
        }
    
        @Override
        public RequestBody toBody(Object value) {
            return RequestBody.create(MediaType.parse("text/plain"), value.toString());
        }
    }
    

    Notes:

    1. ByteString is from Okio library.
    2. Mind the Charset in your MediaType
    0 讨论(0)
提交回复
热议问题