我想使用Apache HTTP客戶端發出Http POST請求。我試圖將HTTP POST請求的內容(在我的應用程序中接收)複製到另一個HTTP POST請求(從我的應用程序發起到另一個URL)。代碼如下所示:設置HTTP POST請求的內容長度
httpPost = new HttpPost(inputURL);
// copy headers
for (Enumeration<String> e = request.getHeaderNames(); e.hasMoreElements();) {
String headerName = e.nextElement().toString();
httpPost.setHeader(headerName, request.getHeader(headerName));
}
BufferedInputStream clientToProxyBuf = new BufferedInputStream(request.getInputStream());
BasicHttpEntity basicHttpEntity = new BasicHttpEntity();
basicHttpEntity.setContent(clientToProxyBuf);
basicHttpEntity.setContentLength(clientToProxyBuf.available());
httpPost.setEntity(basicHttpEntity);
HttpResponse responseFromWeb = httpclient.execute(httpPost);
基本上,我想實現的代理應用程序,它會得到一個URL作爲參數,剛愎請求的URL,然後服務於個性化的外觀網頁等和感覺。
這裏request
是HttpServletRequest。我在設置內容長度時遇到問題。通過調試,我發現clientToProxyBuf.available()
沒有給我正確的輸入流長度,我得到了Http error 400 IE和Error 354 (net::ERR_CONTENT_LENGTH_MISMATCH): The server unexpectedly closed the connection
。
我做錯了嗎?有沒有其他方法可以實現它?
我在我的應用程序中使用StringEntity類。我們應該如何在StringEntity中設置內容長度? – 2015-12-10 09:51:18