Retrofit 2.0 beta1:如何发布原始String体

Vit*_*mov 15 java android retrofit

我正在寻找一些方法来使用新的Retrofit 2.0b1发布原始主体的请求.像这样的东西:

@POST("/token")
Observable<TokenResponse> getToken(@Body String body);
Run Code Online (Sandbox Code Playgroud)

据我所知,应该有某种类型的"to-string"转换器,但我还不清楚它是如何工作的.

有一些方法可以使用TypedInput在1.9中实现它,但它在2.0中没有帮助.

PS是的,后端是愚蠢的,据我所知,没有人会为我改变它:(

感谢帮助.

Was*_*sky 38

在Retrofit 2.0.0-beta2中,您可以使用RequestBodyResponseBody使用String数据将主体发布到服务器,并从服务器的响应主体读取String.

首先,您需要在RetrofitService中声明一个方法:

interface RetrofitService {
    @POST("path")
    Call<ResponseBody> update(@Body RequestBody requestBody);
}
Run Code Online (Sandbox Code Playgroud)

接下来,您需要创建一个RequestBodyCall对象:

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);
Run Code Online (Sandbox Code Playgroud)

最后提出请求并阅读响应机构String:

try {
    Response<ResponseBody> response = call.execute();
    if (response.isSuccess()) {
        String strResponseBody = response.body().string();
    }
} catch (IOException e) {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

  • 这应该是有效的答案. (3认同)

Nik*_*ski 7

您应该在Type构建Retrofit使用时为您注册转换器addConverter(type, converter).

Converter<T> 在2.0中使用类似的方法在1.x版本中使用旧的Converter.

StringConverter应该是这样的:

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());
    }
}
Run Code Online (Sandbox Code Playgroud)

笔记:

  1. ByteString 来自Okio图书馆.
  2. 记住Charset你的MediaType