我想用套接字發出http請求,因爲我想測試一下我可以創建我的服務器的套接字數量。所以我使用OutputStream
和InputStream
從我的服務器寫入和讀取。但在第一個響應之後,我無法再從輸入流中讀取數據。你知道如何在不關閉套接字的情況下讀取第二個響應?
這裏是我的代碼:如何重用java.net.socket中的inputstream?
Socket socket = new Socket();
socket.connect(new InetSocketAddress(address, 80), 1000);
socket.setSoTimeout(25*1000);
OutputStream os = socket.getOutputStream();
os.write(getRequest(host)); // some request as bytearray, it has Connection: Keep-Alive in the header
os.flush();
InputStream is = socket.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
String response = IOUtils.toString(bis);
System.out.println("RESPONSE = \n" + response); // this works fine
os.write(getRequestBodyBa()); // send another request, i can see it sent to server with wireshark
os.flush();
// try to read again but it always return empty string
response = IOUtils.toString(bis); // how to read the second response?????
System.out.println("RESPONSE = \n" + response);
os.close();
is.close();
socket.close();
感謝。
但是OP正在使用一個套接字,你怎麼知道他在使用HTTP呢? – Carlo 2013-03-05 17:10:12
那麼,我猜如果「服務器」不是一個Web服務器,那麼我的答案不適用。 – CodeChimp 2013-03-05 17:15:12
我使用Connection:Keep-Alive在標題中發送http請求。 – 2013-03-05 17:18:03