POST body JSON using Retrofit

前端 未结 1 831
孤独总比滥情好
孤独总比滥情好 2021-02-06 00:45

I\'m trying to POST a JSONObject using the Retrofit library, but when I see the request at the receiving end, the content-length is 0.

In the RestService

相关标签:
1条回答
  • 2021-02-06 01:12

    By default, you don't need to set any headers if you want a JSON request body. Whenever you test Retrofit code, I recommend setting .setLogLevel(RestAdapter.LogLevel.FULL) on your instance of RestAdapter. This will show you the full request headers and body as well as the full response headers and body.

    What's occurring is that you are setting the Content-type twice. Then you're passing a JSONObject, which is being passed through the GsonConverter and mangled to look like {"nameValuePairs":YOURJSONSTRING} where YOURJSONSTRING contains your complete, intended JSON output. For obvious reasons, this won't work well with most REST APIs.

    You should skip messing with the Content-type header which is already being set to JSON with UTF-8 by default. Also, don't pass a JSONObject to GSON. Pass a Java object for GSON to convert.

    Try this if you're using callbacks:

    @POST("/api/v1/user/controller")
    void registerController(
        @Body MyBundleObject registrationBundle,
        @Header("x-company-device-token") String companyDeviceToken,
        @Header("x-company-device-guid") String companyDeviceGuid,
        Callback<ResponseObject> cb);
    

    I haven't tested this exact syntax.

    Synchronous example:

    @POST("/api/v1/user/controller")
    ResponseObject registerController(
        @Body MyBundleObject registrationBundle,
        @Header("x-company-device-token") String companyDeviceToken,
        @Header("x-company-device-guid") String companyDeviceGuid);
    
    0 讨论(0)
提交回复
热议问题