Retrofit 2.0 beta1: how to post raw String body

后端 未结 2 1418
隐瞒了意图╮
隐瞒了意图╮ 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 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 call = retrofitService.update(requestBody);
    

    And finally make a request and read response body as String:

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

提交回复
热议问题