使用DefaultHttpClientConnection發送http發佈請求。是否有可能重用http連接?例如,實例化並設置連接並將套接字綁定到該連接,然後將其分配給該類中的靜態字段。然後對於每個函數調用發送一個http文章,我只是重複使用我之前設置的相同的DefaultHttpClientConnection。我試圖重複使用它,但我不斷收到HTTPException,說我有無效的協議。如果我實例化一個新的DefaultHttpClientConnection,並在每次發送帖子時設置它,代碼就能正常工作,但每當我嘗試提高效率並重用它時,我都會得到該異常。在類對象中保持HTTPClientConnection打開
這是用Java編寫的。
/*
* These settings shall speed up the sending of the http request...
* */
BasicHttpParams params = new BasicHttpParams();
//Use HTTP 1.1 so we open a TCP connection per request sent
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
//Turn off Nagle's Algorithm to speed things up
HttpConnectionParams.setTcpNoDelay(params, true);
params.setBooleanParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
params.setBooleanParameter(HttpConnectionParams.STALE_CONNECTION_CHECK, false);
params.setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE, 8 * 1024);
client.setParams(params);
DefaultConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();
HttpResponse resp = null;
if (conn == null)
{
executor = new HttpRequestExecutor();
context = new BasicHttpContext();
httpproc = new BasicHttpProcessor();
/*Set http connection processors, mostly default settings
* What these protocols do, can be easily found online ;) */
httpproc.addInterceptor(new RequestContent());
httpproc.addInterceptor(new RequestTargetHost());
// Recommended protocol interceptors
httpproc.addInterceptor(new RequestConnControl());
httpproc.addInterceptor(new RequestUserAgent());
httpproc.addInterceptor(new RequestExpectContinue());
}
conn = new DefaultHttpClientConnection();
if (!conn.isOpen())
{
//Opening the socket
try
{
socket = new Socket(request.getURI().getHost(), request.getURI().getPort());
try
{
//Bind socket to the connection
TTLog.log("connection binding to socket...");
conn.bind(socket, client.getParams());
}
catch (IOException e1)
{
TTLog.log("Failed to bind the socket to the HTTPConnection...");
e1.printStackTrace();
}
}
catch (UnknownHostException e1)
{
TTLog.log("The host name is invalid... Hostname: " + request.getURI().getHost());
e1.printStackTrace();
}
catch (IOException e1)
{
TTLog.log("I/O Error when creating socket...");
e1.printStackTrace();
}
}
這裏的例外:
org.apache.http.ProtocolException:不是有效的協議版本:??)»在 org.apache.http.impl.io.AbstractMessageParser大號 .parse(AbstractMessageParser.java:181) 在 org.apache.http.impl.AbstractHttpClientConnection.receiveResponseHeader(AbstractHttpClientConnection.java:185) 在 org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:284 ) 在 org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:126)
此代碼是我如何設置當前完成的連接。每次調用方法時,我都會創建一個新的DefaultHttpClientConnection。試圖避免這種情況,並將DefaultHttpClientConnection保留在類中的靜態變量上。 –
對不起。我編輯的問題與我試圖重複使用時得到的異常一樣。 –
當我執行executor.execute時發生異常。 –