0

我想用套接字发出 http 请求,因为我想测试我可以创建多少个套接字。OutputStream所以我使用and从我的服务器写入和读取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();

谢谢。

4

2 回答 2

1

IOUtils.toString(InputStream) reads the stream to EOS, so there can't be anything left to read for next time. Don't use it. You need to parse the response headers, work out whether there is a Content-Length header, if so read the body for exactly that many bytes; if there is no Content-Length header (and no chunking) the connection is closed after the body so you can't send a second command; etc etc etc. It is endless. Don't use a Socket for this either: use an HTTP URL and URLConnection.

于 2013-03-06T03:10:13.007 回答
1

我相信 HTTP 标准是在每次响应后关闭连接,除非请求的Connection 标头设置为 keep-alive

于 2013-03-05T17:06:39.100 回答