我正在嘗試使用阿帕奇4.5.6上傳一個(gè)通路: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);上傳需要身份驗(yàn)證,在我的情況下,我不知道服務(wù)器是使用摘要式身份驗(yàn)證還是基本身份驗(yàn)證,因此客戶端會(huì)自動(dòng)發(fā)送多個(gè)請求來確定身份驗(yàn)證方案。但是是不可重復(fù)的 ,導(dǎo)致以下錯(cuò)誤:InputStreamEntityorg.apache.http.client.NonRepeatableRequestException: Cannot retry request with a non-repeatable request entity.想法#1:緩沖輸入流我可以包裝實(shí)體,使其可重復(fù):BufferedHttpEntity..BufferedHttpEntity entity = new BufferedHttpEntity(new InputStreamEntity(inputStream));method.setEntity(entity);....但隨后流首先被緩沖,然后全部發(fā)送,而不是分塊/流。這不適用于較大的文件。想法#2:先發(fā)制人的身份驗(yàn)證我可以添加具有正確身份驗(yàn)證的硬編碼標(biāo)頭,以防止重復(fù)請求。但正如我所說,我不知道身份驗(yàn)證方案。想法#3:虛擬文件實(shí)體上傳以獲取上下文(我當(dāng)前的解決方案)我首先上傳一個(gè)空文件,收集上下文并將其添加到我的輸入流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);它有效,但它似乎是一個(gè)黑客。我應(yīng)該這樣做嗎?還有其他選擇嗎?
1 回答

猛跑小豬
TA貢獻(xiàn)1858條經(jīng)驗(yàn) 獲得超8個(gè)贊
請改為激活握手。expect-continue
HttpClientContext context = HttpClientContext.create();
RequestConfig config = RequestConfig.custom().setExpectContinueEnabled(true).build();
context.setRequestConfig(config);
添加回答
舉報(bào)
0/150
提交
取消