【问题标题】:java.net.ProtocolException: unexpected end of stream happened when i uploaded a image to server by okhttpjava.net.ProtocolException:当我通过 okhttp 将图像上传到服务器时发生意外的流结束
【发布时间】:2018-05-05 21:33:46
【问题描述】:

当我上传一个115KB的图片文件到服务器时发生错误。(stackoverflow的大多数答案是关于下载文件。我不知道是否与那些相同) 错误信息如下: onFailure : java.net.ProtocolException: 流的意外结束

相关代码:

public void upLoadImageFile(String uploadUrl, File file, Map<String, String> maps, final HWUploadListener listener) {


    final CallbackHandler handler = new CallbackHandler(listener);

    try {
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        if (maps == null) {
            builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"image\";filename=\"file.jpg\""),
                    RequestBody.create(MediaType.parse("image/jpeg"), file)).build();

        } else {
            for (String key : maps.keySet()) {
                builder.addFormDataPart(key, maps.get(key));
            }
            builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"image\";filename=" + file.getName()), RequestBody.create(MediaType.parse("image/jpeg"), file)
            );
        }


        RequestBody body = builder.build();

        final Request request = new Request.Builder().url(uploadUrl).post(body).build();

        final Call call = mOkHttpClient.newBuilder().writeTimeout(50, TimeUnit.SECONDS).build().newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                UtilUtils1.log("HuowuSdk", "onFailure :" + e.toString());
                handler.uploadFailure(e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                if (response.isSuccessful()) {
                    String result = response.body().string();
                    handler.uploadSuccess(result);

                } else {
                    handler.uploadFailure(response.message());
                }
            }
        });

    } catch (Exception e) {
        UtilUtils1.log("HuowuSdk", e.toString());
        handler.uploadError(e.toString());
    }
}

感谢您的回答!

【问题讨论】:

    标签: java android image upload okhttp


    【解决方案1】:

    在下面的这一行中,您必须增加写入超时,因为在上传时您的写入超时到期可能是原因,因此在下面的行中增加 writeTimeout 限制:

    final Call call = mOkHttpClient.newBuilder().writeTimeout(50, TimeUnit.SECONDS).build().newCall(request);
    

    【讨论】:

    • 感谢您的回答。但我之前已经写了超时限制。问题仍然存在。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-23
    • 2015-11-17
    • 1970-01-01
    • 2017-11-12
    • 1970-01-01
    • 2019-05-14
    • 2019-01-20
    相关资源
    最近更新 更多