我正在創建一個HTTP客戶端,它處理HTTP請求和使用套接字的響應。它能夠發送第一個請求並讀取響應流。但是後續請求不會寫入任何內容到輸入流。多個HTTP請求/ w單個套接字
static String host/* = some host*/;
static int port/* = some port*/;
private Socket sock = null;
private BufferedWriter outputStream = null;
private BufferedReader inputStream = null;
public HttpClient() throws UnknownHostException, IOException {
sock = new Socket(host, port);
outputStream = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
inputStream = new BufferedReader(new InputStreamReader(sock.getInputStream()));
sock.setKeepAlive(true);
sock.setTcpNoDelay(true);
}
/* ... */
public String sendGetRequest(String relAddr) throws IOException {
outputStream.write("GET " + relAddr + " HTTP/1.0\r\n");
outputStream.write("\r\n");
outputStream.flush();
String line;
StringBuffer buff = new StringBuffer();
while((line = inputStream.readLine()) != null) {
buff.append(line);
buff.append("\n");
}
return buff.toString();
}
在main方法,我使用下面的:
client = new HttpClient();
str = client.sendGetRequest(addr);
System.out.println(str);
/* and again */
str = client.sendGetRequest(addr);
System.out.println(str);
但只有第一sendGetRequest調用返回一個響應字符串。後來的人沒有。你有好主意嗎?
對於每個請求,您應該可以對輸入/輸出流進行「打開()」和「關閉()」...即使套接字被重用。 – Marcelo 2012-03-21 15:07:06
實際上,如果我在每次請求之前重新創建客戶端對象,那麼一切都很完美。不過,我希望這個套接字是持久的。 – 2012-03-21 15:16:14
@Marcelo那會關閉插座。 – EJP 2012-03-21 21:17:54