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

前端 未结 23 2354
面向向阳花
面向向阳花 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:42

    Solved my problem based on TommySM answer (see previous). But I didn't need to make login, I used Retrofit2 for testing https GraphQL API like this:

    1. Defined my BaseResponse class with the help of json annotations (import jackson.annotation.JsonProperty).

      public class MyRequest {
          @JsonProperty("query")
          private String query;
      
          @JsonProperty("operationName")
          private String operationName;
      
          @JsonProperty("variables")
          private String variables;
      
          public void setQuery(String query) {
              this.query = query;
          }
      
          public void setOperationName(String operationName) {
              this.operationName = operationName;
          }
      
          public void setVariables(String variables) {
              this.variables = variables;
          }
      }
      
    2. Defined the call procedure in the interface:

      @POST("/api/apiname")
      Call apicall(@Body RequestBody params);
      
    3. Called apicall in the body of test: Create a variable of MyRequest type (for example "myLittleRequest").

      Map jsonParams = convertObjectToMap(myLittleRequest);
      RequestBody body = 
           RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),
                          (new JSONObject(jsonParams)).toString());
      response = hereIsYourInterfaceName().apicall(body).execute();
      

提交回复
热议问题