[英]How to append api key body in the interceptor on a post request using retrofit
我正在尝试使用拦截器将Api密钥附加到请求的主体中。 我尝试了各种方法,但都无济于事。
网址: https : //someapi.com/api/stories/
方法:开机自检
标题:接受:application / json
输入:{“ key”:“”}
@提供@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;
}
}
Retrofit2的可能重复项:在OkHttp Interceptor中修改请求正文
@Debanjan的最后一个答案提供了一个很好的解决方案,它涵盖了application / json和表单数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.