如何使用OKHttp使用空体进行POST

时间:2017-01-25 06:24:50

标签: java android okhttp3

我面对不同的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();
}

2 个答案:

答案 0 :(得分:0)

它正在进行改造,所以如果你继续使用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();
            }
        };
    }
}

答案 1 :(得分:-1)

尝试使用以下代码,这可能会有所帮助。

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

OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
        .url("http://ap.imagensbrasil.org/api/1/upload/?key=9c9dfe77cd3bdbaa7220c6bbaf7452e7&source=" + image64 + "&format=txt")
        .post("")
        .build();