okhttp3 - 413 请求实体太大

Mau*_*ves 2 java request okhttp http-status-code-413

当我的系统使用 okhttp3 发送 http 请求时,会出现以下问题:413 Request Entity Too Large

我想知道如何在 okhttp3 请求中设置最大大小,或者是否有其他解决方案来解决此问题。

public static String post(String url, String json) throws IOException {
    OkHttpClient client = new OkHttpClient().newBuilder()
            .readTimeout(1, TimeUnit.MINUTES)
            .build();
    RequestBody body = RequestBody.create(JSON, json);
    Request request = new Request.Builder()
    .header("Authorization", authKey)
    .url(url)
    .post(body)
    .build();
    try (Response response = client.newCall(request).execute()) {
        if(response.code() != 200) {
            return "request error";
        }
        return response.body().string();
    }
}
Run Code Online (Sandbox Code Playgroud)

per*_*vic 6

这实际上并不是您的代码的问题,而是您向其发送数据的服务器对请求负载大小有限制。有关错误的详细信息,请参阅:HTTP 响应状态代码 413:有效负载太大

如果您控制服务器,则可以调整此设置。可以在此处找到修复几个常见服务器(Apache、NGINX、IIS)的此错误的示例 。

如果您无法控制,您可能需要查看您正在使用的服务的 API/文档,以了解上传数据的其他方式。该服务可能只是对该​​特定用例的有效负载大小有严格的限制。