改造 POST。向每个 post 请求添加 JSON 参数

Retrofit POST. Add JSON parameter to every post request

我有四个静态参数,我只需要为每个 post 改造请求设置一次,因为我不需要每次都将它们放在每个请求中。这是我的代码:

  public interface Login {
        @POST("login")
        @Headers("Content-Type: application/json")
        Call<String> login(@Body JsonObject json);
    }

然后我调用它并将电子邮件和密码作为正文参数传递,如下所示:

  private void sendLoginRequest() {
    API.login().login(CommandLogin.getInputParamsAsJSON(mStrEmail, Utils.md5(mStrPassword))).enqueue(this);
}

然后在 intercept body 中我试图传递这个静态参数,但是当我检查 log 时它似乎只传递了这两个没有电子邮件和密码的静态参数。在我的情况下,我想输入 body email,password,os,版本.

public class API {

private static <T> T builder(Class<T> endpoint) {
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

    OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .addInterceptor(
                    new Interceptor() {
                        @Override
                        public Response intercept(Interceptor.Chain chain){
                            try {
                                Request original = chain.request();

                                JSONObject params = new JSONObject();
                                params.put("version"        , "6");
                                params.put("os"             , "2");

                                MediaType JSON = MediaType.parse("application/json; charset=utf-8");
                                RequestBody body = RequestBody.create(JSON, params.toString());

                                Request.Builder requestBuilder = original.newBuilder()
                                        .post(body);

                                Request request = requestBuilder.build();

                                return chain.proceed(request);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            //TODO
                            return null;
                        }
                    })
            .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
            .build();

    return new Retrofit.Builder()
            .baseUrl(Utils.BASE_COMPONENT_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .client(okHttpClient)
            .build()
            .create(endpoint);
}



public static Login login() {
    return builder(Login.class);
}

}

那是因为,您基本上是用新参数覆盖原始登录 Post 请求正文。您应该做的是,从原始请求中获取 post 正文并将新参数附加到它。

类似下面的内容(代码未测试)

try {
    // Create new buffer
    final Buffer buffer = new Buffer();

    // Copy original request's json body to buffer
    chain.request().body().writeTo(buffer);

    // Convert buffer to JSONObject
    JSONObject params = new JSONObject(buffer.readUtf8());

    // Append new params
    params.put("version", "6");
    params.put("os", "2");

    // Now the params json object will have all 4 values: email,password,os,version

    // TODO: Your remaining code

} catch (Exception ex) {
    Log.d("Login","Error creating post body", ex);
}