HTTPリクエストとレスポンスをソケットで処理するHTTPクライアントを作成しています。最初の要求を送信し、応答ストリームを読み取ることができます。しかし、後続の要求は入力ストリームに何も書き込まない。 mainメソッドで複数の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();
}
、私は以下を使用:
client = new HttpClient();
str = client.sendGetRequest(addr);
System.out.println(str);
/* and again */
str = client.sendGetRequest(addr);
System.out.println(str);
しかし、唯一の第sendGetRequestの呼び出しは、応答文字列を返します。後続のものはそうしない。アイデアはありますか?
ソケットが再利用されているにもかかわらず、すべての要求に対して入出力ストリームを 'open()'と 'close()するべきです。 – Marcelo
実際には、各リクエストの前にクライアントオブジェクトを再作成すると、すべてが完全に機能します。しかし、私はそのソケットを永続化したい。 –
@Marceloいいえ、それはソケットを閉じるでしょう。 – EJP