Retrofit Post request parameter is Json

Keywords: OkHttp JSON Retrofit Linux

Description of Retrofit Request Post Request Parameters

1. Description:

Retrofit network framework uses annotations to support multiple requests, and the request parameters are also implemented by annotations. This paper mainly describes the parameter settings of Post requests, involving annotations @Field,@FieldMap,@FormUrlEncoded,@Body.

2. POST Request Profile:

HTTP requests are GET, POST, PUT, DELETE, HEAD, OPTIONS... GET requests use plaintext URL s to obtain corresponding resources at the server side, PUT requests to add a new data for the server, DELETE requests to delete a data at the server side, HEAD requests only return to the request head, which can detect whether the accessed resources exist; POST requests are in the form of form data, etc., accessing the server side by the requester, requesting the server to process:

  1. POST sends data to the server for processing. The data is contained in the HTTP message body.
  2. POST requests submit data to specified resources, and request servers process it, such as form data submission, file upload, etc. Request data will be included in the body of the request.
  3. POST methods may create new resources or/or modify existing resources.
  4. When using the POST method, the query string exists separately in the POST information and is sent to the server along with the HTTP request: for example
    POST /test/demoform.html HTTP/1.1
    Host: w3schools.com
    name1=value1&name2=value2
    

Our POST request parameter name1 = value1 & Name2 = Value2 is carried in the body of the request rather than appended directly to the end of the url, which is also the biggest difference from GET requests.

  • POST features:
  1. POST requests cannot be cached
  2. POST requests are not saved in browser browsing records
  3. The URL requested with POST cannot be saved as a browser bookmark
  4. POST requests have no length limit

3. Retrofit POST request example:

The interface specification is shown as follows:

So the request is POST type, JSON format submits data, and requires request header parameters

3.1 Building Interface Classes

Therefore, the Retrofit interface class is constructed as follows: (here includes the way to submit data in the form of key-value pairs and json data)

    interface Api {
        /**
         * Use the @Body annotation as a parameter
         */
        @POST("/user/updateUserInfo")
        Observable<BaseModel> updateUserInfo3(@Body RequestBody body);
        
        /**
         * Use the @Field annotation as a parameter
         */
        @FormUrlEncoded //@ The Field parameter must require this annotation
        @POST("/user/updateUserInfo")
        Observable<BaseModel> updateUserInfo1(@Field("phone") String phone, @Field("isUpdated") String isUpdated);

        /**
         * Use the @FieldMap annotation as a parameter
         */
        @POST("/user/updateUserInfo")
        Observable<BaseModel> updateUserInfo2(@FieldMap() Map param);
    }

3.2 Request Result Display

  1. @Body annotation
    Method 1: Obtain json data using objects

        UserInfoBean userInfoBean = new UserInfoBean("18808086666", "1");
        RequestBody body = FormBody.create(MediaType.parse("application/json; charset=utf-8"), new Gson().toJson(userInfoBean));
        //Interface object instance calls related interface to obtain Observable object
        Observable<BaseModel> observable = api.updateUserInfo3(body);
    

    Method 2: Use map to get json data

        HashMap<String, Object> map = new HashMap<>();
        map.put("phone", "18808086666");
        map.put("isUpdated", "1");
        RequestBody requestBody = RequestBody.create(MediaType.parse("Content-Type, application/json"), new JSONObject(map).toString());
        //Interface object instance calls related interface to obtain Observable object
        Observable<BaseModel> observable = api.updateUserInfo3(body);
    

    Log results:

    D/OkHttp: --> POST http://****/user/updateUserInfo http/1.1
    D/OkHttp: Content-Length: 39
    D/OkHttp: User-Agent: Mozilla/5.0 (Linux; Android 9; COL-AL10 Build/HUAWEICOL-AL10; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/71.0.3578.99 Mobile Safari/537.36
    D/OkHttp: Authorization: M2I0OTU4OTQ3NjY0MDNmURRmNmUwN2Qw 
    D/OkHttp: {"phone":"18808086666","isUpdated":"1"}
    D/OkHttp: --> END POST (39-byte body)
    D/OkHttp: <-- 200  http://****/user/updateUserInfo (40ms)
    D/OkHttp: Content-Type: application/json;charset=UTF-8
    D/OkHttp: Transfer-Encoding: chunked 
    D/OkHttp: Date: Fri, 26 Apr 2019 03:36:15 GMT
    D/OkHttp: Cache-Control: public, max-age=3600
    D/OkHttp: {"code":"1000","msg":"Request successful","data":""}
    D/OkHttp: <-- END HTTP (46-byte body)
    

    Focus on: {"phone": "188086666", "isUpdated": "1"}, indicating that the submission parameter is a json string

  2. @Field annotation
    Invoke interface, pass in parameters

    	Observable<BaseModel> observable = api.updateUserInfo1("18808086666", "1");
    

    Log results

    	D/OkHttp: --> POST http://****/user/updateUserInfo http/1.1
    	D/OkHttp: Content-Type: application/x-www-form-urlencoded
    	D/OkHttp: Content-Length: 29
    	D/OkHttp: User-Agent: Mozilla/5.0 (Linux; Android 9; COL-AL10 Build/HUAWEICOL-AL10; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/71.0.3578.99 Mobile Safari/537.36
    	D/OkHttp: Authorization: M2I0OTU4OTQ3NjY0MDNmURRmNmUwN2Qw 
    	D/OkHttp: phone=18808086666&isUpdated=1
    	D/OkHttp: --> END POST (29-byte body)
    	D/OkHttp: <-- 415  http://****/user/updateUserInfo (31ms)
    	D/OkHttp: Content-Type: application/json;charset=UTF-8
    	D/OkHttp: Transfer-Encoding: chunked
    	D/OkHttp: Date: Fri, 26 Apr 2019 06:53:47 GMT
    	D/OkHttp: Cache-Control: public, max-age=3600
    	D/OkHttp: {"timestamp":1556261627312,"status":415,"error":"Unsupported Media Type","message":"Content type 'application/x-www-form-urlencoded' not supported","path":"/user/updateUserInfo"}
    	D/OkHttp: <-- END HTTP (178-byte body)
    

    Focus on: phone = 188086666 & isUpdated = 1, which is the form of key-value pairs to submit data;
    The final result is: the error code 415, Unsupported Media Type, and pointed out that the content type of the request is Content type'application/x-www-form-urlencoded', which is quite different from the Content-Type: application/json above.

  3. @ FieldMap annotations
    Similar to @Field, the difference is that the request parameter is map.

    HashMap<String, Object> map = new HashMap<>();
    map.put("phone", "18808086666");
    map.put("isUpdated", "1");
    Observable<BaseModel> observable = api.updateUserInfo2(map);
    

    The same is true for log results.

4 Summary:

  1. @ File,@FieldMap parameter submission type is'application/x-www-form-urlencoded'
  2. @ The type of submission of the Body parameter is'application/json'
  3. As a developer, you need to clarify the details of front-end and back-end interfaces thoroughly before you develop requirements; this example involves request mode, request header, request parameter type, and so on; if you understand the deviation, you will make a mistake of course.

Posted by spfoonnewb on Sat, 27 Apr 2019 10:00:35 -0700