多个HTTP请求/ w单个套接字

时间:2012-03-21 14:58:34

标签: java http sockets

我正在创建一个HTTP客户端,它使用套接字处理HTTP请求和响应。它能够发送第一个请求并读取响应流。但是后续请求不会向输入流写入任何内容。

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调用才会返回响应字符串。后续的没有。你有什么想法吗?

1 个答案:

答案 0 :(得分:1)

HTTP 1.0不支持持久连接作为实际规范的一部分(显然有unofficial extension)。您需要切换到1.1(或使用非官方扩展,假设服务器支持它)。