2015-09-18 3 views
12

新しいRetrofit 2.0b1を使用して生のボディでリクエストを投稿する方法を探しています。このような何か:Retrofit 2.0 beta1:生のStringボディを投稿する方法

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

私の知る限り理解し、海峡のいくつかの種類があるはずです「と、文字列」コンバータが、それは、それがどのように動作するかはまだ私のため明らかではありません。

TypedInputで1.9でそれを実現させる方法がありましたが、それはもはや2.0では役に立ちません。

PSはい、バックエンドは限り私は誰もが私のためにそれを変更しません:(助けを

感謝を見るように、愚かである。

答えて

7

作成しているとき、あなたはあなたのTypeのためのコンバータを登録する必要があります2.0でaddConverter(type, converter)

Converter<T>を使用してRetrofitは1.xのバージョンでは、古いコンバーターを使用して、同様のアプローチを使用しています。

あなた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ライブラリからである。このようなものになるULD。あなたがStringデータを使用してサーバーに身体を投稿するRequestBodyResponseBodyを使用してStringとして、サーバーの応答本体から読み取ることができるレトロフィット2.0.0ベータ2では、あなたのMediaType
+0

ちょうどそれを行う方法を見つけました。ありがとう! –

23

  • マインドCharset

    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); 
    

    そして最後に要求を行うととレスポンスボディを読む:あなたがRequestBodyCallオブジェクトを作成する必要が

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

    次へ:

    まず、あなたのRetrofitServiceでメソッドを宣言する必要がありますString

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

    ありがとうございます。ニースの解決策 –

    +0

    これは有効な答えでなければなりません。 –

    関連する問題