我正在尝试使用拦截器将Api密钥附加到请求的正文中。我尝试了各种方法,但都无济于事。
URL:https://someapi.com/api/stories/
方法:开机自检
头:接受:application / json
输入:{“ key”:“”}
@Provides @辛格尔顿 公共拦截器拦截器(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;
}
}
答案 0 :(得分:0)
可能的Retrofit2: Modifying request body in OkHttp Interceptor副本
@Debanjan的最后一个答案提供了一个很好的解决方案,涵盖了application / json和表单数据。