Retrofit 2.0 beta1:如何 post raw String body

Retrofit 2.0 beta1: how to post raw String body

我正在寻找一些方法来 post 使用新的 Retrofit 2.0b1 请求原始主体。像这样:

@POST("/token")
Observable<TokenResponse> getToken(@Body String body);

据我所知,应该有某种简单的“到字符串”转换器,但我还不清楚它是如何工作的。

在 1.9 中有一些方法可以使用 TypedInput 实现它,但它在 2.0 中不再有用。

当您使用 addConverter(type, converter) 构建 Retrofit 时,您应该为 Type 注册一个转换器。

2.0 中的

Converter<T> 使用与 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());
    }
}

备注:

  1. ByteString 来自 Okio 图书馆。
  2. 注意 MediaType
  3. 中的 Charset

在 Retrofit 2 中,您可以使用 RequestBodyResponseBody 到 post 使用 String 数据的主体到服务器,并从服务器的响应主体读取为 String.

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

interface RetrofitService {
    @POST("path")
    Call<ResponseBody> update(@Body RequestBody requestBody);
}

接下来您需要创建一个 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);

最后发出请求并读取响应体 String:

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