java使用jackrabbit去做webdav上传文件时出现Connection reset by peer: socket write error问题

陈昊昊
2023-12-01

发现使用域名去请求上传文件时,没有问题,后来想提升上传速度,就换成内网ip去请求上传,但是请求后会出现 java.net.SocketException: Connection reset by peer: socket write error的问题,后面又通过postman直接用ip请求发现也是没有问题的,所以对比查看一下jackrabbit和httpclient的源码,发现是ip地址请求时没有对 content-length做处理,具体再深层次的原因应该socket连接的问题,目前自己还没完全吃透,所以就不做详细解释了,免得说错误导大家,如果有知道的朋友可以一起讨论一下。

实现代码如下:

// 上传文件
HttpPut put = new HttpPut(webDavConfig.getBaseUrl() + webDavConfig.getDav() + URLEncoder.encode(fullPath, "utf-8"));
InputStreamEntity requestEntity = new InputStreamEntity(new FileInputStream(file), file.length());
// 在这里设置 content-length 如果在后面通过 put.addHeader()或put.setHeader()的方式设置content-length,会再次报错提示content-length已存在
put.setEntity(requestEntity);
HttpResponse putResponse = client.execute(put, context);
int putStatus = putResponse.getStatusLine().getStatusCode();

if (putStatus == HttpStatus.CREATED.value()) {
    log.info("### web dav upload file:{} success", fullPath);
    // 上传成功后获取分享链接
    HttpPost post = new HttpPost(webDavConfig.getBaseUrl() + webDavConfig.getShare() + "?path=" + webDavConfig.getRootDir() + URLEncoder.encode(fullPath, "utf-8"));
    HttpResponse postResponse = client.execute(post, context);
    int postStatus = postResponse.getStatusLine().getStatusCode();

    if (postStatus == HttpStatus.OK.value()) {
        HttpEntity entity = postResponse.getEntity();
        DavResponseBean responseBean = JSONObject.parseObject(EntityUtils.toString(entity), DavResponseBean.class);
        Integer code = responseBean.getCode();
        if (code != null && code == ResponseCode.SUCCESS.getCode()) {
            DavResponseDataBean data = responseBean.getData();
            if (data != null) {
                String sharePath = data.getUrl();
                response.setData(sharePath);
            }
        } else {
            log.info("### web dav get file:{} share url fail:{}", fullPath, responseBean.getMsg());
            return ResponseUtils.error();
        }
    } else {
        log.info("### web dav get file:{} share url fail:{}", fullPath, JSONObject.toJSONString(postResponse.getStatusLine()));
        return ResponseUtils.error();
    }

} else {
    log.info("### web dav upload file:{} fail:{}", fullPath, JSONObject.toJSONString(putResponse.getStatusLine()));
    return ResponseUtils.error();
}
 类似资料: