为了账号安全,请及时绑定邮箱和手机立即绑定

如何通过 HttpPut 从 Apache 上传输入流 4.x

如何通过 HttpPut 从 Apache 上传输入流 4.x

烙印99 2022-09-22 13:50:48
我正在尝试使用阿帕奇4.5.6上传一个通路:InputStreamHttpPutInputStream inputStream = ..CredentialsProvider provider = ..HttpClient client = HttpClientBuilder.create()                .setDefaultCredentialsProvider(provider)                .build();HttpPut method = new HttpPut("MY_REMOTE_URL");InputStreamEntity entity = new InputStreamEntity(inputStream);method.setEntity(entity);client.execute(method);上传需要身份验证,在我的情况下,我不知道服务器是使用摘要式身份验证还是基本身份验证,因此客户端会自动发送多个请求来确定身份验证方案。但是是不可重复的 ,导致以下错误:InputStreamEntityorg.apache.http.client.NonRepeatableRequestException: Cannot retry request with a non-repeatable request entity.想法#1:缓冲输入流我可以包装实体,使其可重复:BufferedHttpEntity..BufferedHttpEntity entity = new BufferedHttpEntity(new InputStreamEntity(inputStream));method.setEntity(entity);....但随后流首先被缓冲,然后全部发送,而不是分块/流。这不适用于较大的文件。想法#2:先发制人的身份验证我可以添加具有正确身份验证的硬编码标头,以防止重复请求。但正如我所说,我不知道身份验证方案。想法#3:虚拟文件实体上传以获取上下文(我当前的解决方案)我首先上传一个空文件,收集上下文并将其添加到我的输入流PUT请求中:HttpPut testMethod = new HttpPut("MY_REMOTE_DUMMY_URL");FileEntity testEntity = new FileEntity(testFile);testMethod.setEntity(testEntity);HttpContext context = new BasicHttpContext();client.execute(testMethod, context);// .. delete the testEntity from server ..HttpPut method = new HttpPut("MY_REMOTE_URL");InputStreamEntity entity = new InputStreamEntity(inputStream);method.setEntity(entity);client.execute(method, context);它有效,但它似乎是一个黑客。我应该这样做吗?还有其他选择吗?
查看完整描述

1 回答

?
猛跑小猪

TA贡献1858条经验 获得超8个赞

请改为激活握手。expect-continue


HttpClientContext context = HttpClientContext.create();

RequestConfig config = RequestConfig.custom().setExpectContinueEnabled(true).build();

context.setRequestConfig(config);


查看完整回答
反对 回复 2022-09-22
  • 1 回答
  • 0 关注
  • 173 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号