Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/369.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 多个HTTP请求/w单个套接字_Java_Http_Sockets - Fatal编程技术网

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

Java 多个HTTP请求/w单个套接字,java,http,sockets,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 = n

我正在创建一个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();
}
在主要方法中,我使用以下方法:

client = new HttpClient();
str = client.sendGetRequest(addr);
System.out.println(str);
/* and again */
str = client.sendGetRequest(addr);
System.out.println(str);

但只有第一个sendGetRequest调用返回响应字符串。后面的那些没有。您有什么想法吗?

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

您可能应该
open()
close()
为每个请求提供输入/输出流。。。实际上,如果我在每次请求之前重新创建客户机对象,一切都会很好地工作。不过我希望那个套接字是持久的。@Marcelo不。那会关闭套接字。@EdwardThomson-补充了说明,直到关于将alives保持在HTTP 1.0下。这是公平的。我承认它不在HTTP/1.0规范中,但值得指出的是,即使是Apache和IIS的古老版本也支持HTTP/1.0.Up投票和无法解释的downvote。答案是正确的;无法解释的否决票通常是不正确的,就像这里一样。