How to POST raw whole JSON in the body of a Retrofit request?

前端 未结 23 2381
面向向阳花
面向向阳花 2020-11-22 00:57

This question may have been asked before but no it was not definitively answered. How exactly does one post raw whole JSON inside the body of a Retrofit request?

See

23条回答
  •  囚心锁ツ
    2020-11-22 01:33

    The @Body annotation defines a single request body.

    interface Foo {
      @POST("/jayson")
      FooResponse postJson(@Body FooRequest body);
    }
    

    Since Retrofit uses Gson by default, the FooRequest instances will be serialized as JSON as the sole body of the request.

    public class FooRequest {
      final String foo;
      final String bar;
    
      FooRequest(String foo, String bar) {
        this.foo = foo;
        this.bar = bar;
      }
    }
    

    Calling with:

    FooResponse = foo.postJson(new FooRequest("kit", "kat"));
    

    Will yield the following body:

    {"foo":"kit","bar":"kat"}
    

    The Gson docs have much more on how object serialization works.

    Now, if you really really want to send "raw" JSON as the body yourself (but please use Gson for this!) you still can using TypedInput:

    interface Foo {
      @POST("/jayson")
      FooResponse postRawJson(@Body TypedInput body);
    }
    

    TypedInput is a defined as "Binary data with an associated mime type.". There's two ways to easily send raw data with the above declaration:

    1. Use TypedByteArray to send raw bytes and the JSON mime type:

      String json = "{\"foo\":\"kit\",\"bar\":\"kat\"}";
      TypedInput in = new TypedByteArray("application/json", json.getBytes("UTF-8"));
      FooResponse response = foo.postRawJson(in);
      
    2. Subclass TypedString to create a TypedJsonString class:

      public class TypedJsonString extends TypedString {
        public TypedJsonString(String body) {
          super(body);
        }
      
        @Override public String mimeType() {
          return "application/json";
        }
      }
      

      And then use an instance of that class similar to #1.

提交回复
热议问题