我面临着一个不同的Api服务,我必须使用POST来请求它,但是没有任何正文内容,我正在发送一个转换为base64的图像,我一直在搜索该问题,但是发现了这个“解决方案”,不起作用:
1:
RequestBody reqbody = RequestBody.create(null, new byte[0]);
Request.Builder formBody = new Request.Builder().url(url).method("POST",reqbody).header("Content-Length", "0");
2:
request = new Request.Builder()
.url(BASE_URL + route)
.method("POST", RequestBody.create(null, new byte[0]))
.post(requestBody)
.build();
甚至我明确地说这是POST方法,它始终发送GET请求而不是POST请求。谢谢!
我的活动:
public String SendImage(String image64) throws IOException{
//RequestBody reqbody = RequestBody.create(null, new byte[0]);
Request request = new Request.Builder()
.url("http://ap.imagensbrasil.org/api/1/upload/?key=9c9dfe77cd3bdbaa7220c6bbaf7452e7&source=" + image64 + "&format=txt")
.method("POST", RequestBody.create(null, new byte[0]))
.header("Content-Length", "0")
.build();
OkHttpClient Client = client.newBuilder() .readTimeout(25, TimeUnit.SECONDS).build();
Response response = Client.newCall(request).execute();
return response.body().string();
}
最佳答案
它正在进行改造,因此,如果继续使用Retrofit v2.0,可以使用以下命令:
public class Base64EncodeRequestInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
Request.Builder builder = originalRequest.newBuilder();
if (originalRequest.method().equalsIgnoreCase(POST)) {
builder = originalRequest.newBuilder()
.method(originalRequest.method(), encode(originalRequest.body()));
}
return chain.proceed(builder.build());
}
private RequestBody encode(RequestBody body) {
return new RequestBody() {
@Override
public MediaType contentType() {
return body.contentType();
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
Buffer buffer = new Buffer();
body.writeTo(buffer);
byte[] encoded = Base64.encode(buffer.readByteArray(), Base64.DEFAULT);
sink.write(encoded);
buffer.close();
sink.close();
}
};
}
}