- 您应该将现有库用于HTTP。看这里。
- 您的代码按预期工作。服务器不会关闭连接,并且
dataBuffer
永远不会变为-1
。发生这种情况是因为默认情况下,连接在HTTP 1.1中保持活动状态。使用HTTP 1.0,或Connection: close
在请求中添加标头。
例如:
out.write("GET "+ path +" HTTP/1.1rnHost: "+ host +"rnConnection: closernrn");out.flush();int dataBuffer;while ((dataBuffer = connection.getInputStream().read()) != -1) System.out.print((char)dataBuffer);out.close();


