【问题标题】:How to append api key body in the interceptor on a post request using retrofit如何使用改造在发布请求的拦截器中附加 api 密钥主体
【发布时间】:2019-06-26 10:24:30
【问题描述】:

我正在尝试使用拦截器将 Api 密钥附加到我的请求正文中。各种方法都试过了,都不行。。

网址:https://someapi.com/api/stories/

方法:发布

标题:接受:应用程序/json

输入:{“键”:“”}

@提供 @Singleton 公共拦截器拦截器(NetworkUtils networkUtils){ 返回链-> { 请求 originalRequest = chain.request();

        RequestBody requestBody = networkUtils.createBody();
        String postBodyString = networkUtils.bodyToString(requestBody);
        Request.Builder builder = originalRequest.newBuilder();
        postBodyString += ((postBodyString.length() > 0) ? "&" : "") + networkUtils.bodyToString(requestBody);
        originalRequest = builder.
                post(RequestBody.create(MediaType.parse(Constants.NETWORKING_HEADER.CONTENT_TYPE), postBodyString)).build();
        return chain.proceed(originalRequest);
    };
}


public RequestBody createBody() {
    return new FormBody.Builder()
            .add(Constants.NETWORKING_HEADER.KEY, Constants.NETWORKING_HEADER.API_KEY).build();
}

public 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) {
        String message = "Did not work";
        Timber.d(message);
        return message;
    }
}

【问题讨论】:

    标签: android retrofit


    【解决方案1】:

    Retrofit2: Modifying request body in OkHttp Interceptor 可能重复

    @Debanjan 的最后一个答案提供了一个很好的解决方案,涵盖了 application/json 以及表单数据。

    【讨论】:

      猜你喜欢
      • 2014-03-27
      • 1970-01-01
      • 2018-10-23
      • 2021-11-02
      • 2021-08-15
      • 2016-07-15
      • 2019-06-04
      • 2021-02-15
      • 1970-01-01
      相关资源
      最近更新 更多