Getting Request body content using Retrofit 2.0 POST method

前端 未结 2 1400
遇见更好的自我
遇见更好的自我 2021-02-07 14:13

I have a requirement to get a request body and to perform some logic operations with Retrofit 2.0 before doing enque operation. But unfortunately I am not able to g

相关标签:
2条回答
  • 2021-02-07 14:33

    I have got it working from this link Retrofit2: Modifying request body in OkHttp Interceptor

    private String bodyToString(final RequestBody request) {
                try {
                    final RequestBody copy = request;
                    final Buffer buffer = new Buffer();
                    if (copy != null)
                        copy.writeTo(buffer);
                    else
                        return "";
                    return buffer.readUtf8();
                } catch (final IOException e) {
                    return "did not work";
                }
            }
    

    Retrofit dependencies i am using are

     compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta3'
        compile 'com.squareup.okhttp3:okhttp:3.0.0-RC1'
        compile 'com.squareup.okhttp3:logging-interceptor:3.0.0-RC1'
        compile 'com.squareup.retrofit2:retrofit:2.0.0-beta3'
    
    0 讨论(0)
  • 2021-02-07 14:38

    I too had the similar issue, I had set JSON as @Body type in retrofit, so the namevaluepair appears in front of the raw body, and it can be seen inside the interceptor. Even though if we log/debug the jsonObject.toString we see the request as correct without the namevaluepair presented.

    What i had done was by setting

    Call<ResponseBody> getResults(@Body JsonObject variable);
    

    and in the calling of the method i converted the JSONObject to JsonObject by

     new JsonParser().parse(model).getAsJsonObject();
    
    0 讨论(0)
提交回复
热议问题