Java HttpURLConnection如何接收来自服务器的多个响应

标签 java http httpurlconnection

我正在尝试使用 POST 消息连接到服务器,要求服务器订阅我。然后,服务器将保持 http 连接打开并向我发送带有实时状态的异步消息,直到我请求取消订阅或自己关闭连接。我无法读取来自服务器的这些后续响应。下面的代码确实连接到服务器并成功读取第一个响应并将其打印到控制台。问题是之后它会无限地读取相同的响应(第一个响应)并将其打印到屏幕上。

有人看到我在这里搞砸了什么吗?我试图监视来自服务器的下一条异步消息并阻止直到它到来。另外,如果有人知道如何注册以在下一条消息异步显示时收到通知,这样我就不必阻塞等待,那就更好了。

public void HttpSubscription() 
{
    byte[] result = new byte[10240];

    try
    {
        /* Generate the hard coded request data */
        final StringBuffer soap = new StringBuffer();
        soap.append("<s:Envelope><s:Body><SoapTest1>thing1</SoapTest1></s:Body></s:Envelope>");

        // to make HTTP Post request with HttpURLConnection
        URL url = new URL("http://192.168.1.110:80/services");
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();

        // then set some properties and make a request
        conn.setRequestMethod("POST");
        conn.setRequestProperty( "Content-type", "text/xml; charset=utf-8" );

        // Get a handle to the output stream 
        OutputStream OStream = conn.getOutputStream();

        // Write the soap data to the output stream
        OStream.write(soap.toString().getBytes());

        InputStream ResponseStream = conn.getInputStream();
        while (true)
        {
            int len = ResponseStream.read(result);
            String value = new String(result);
            System.out.println(value);
        }
    }
    catch (Exception e)
    {
        System.out.println(e);
    }

    return;
}

最佳答案

有点旧,但我决定在这里纠正一些公然的错误信息。

关于一个 HTTP 请求的多个响应不符合 HTTP 规范的答案是错误的!

来自RFC 2616 :

10 Status Code Definitions

Each Status-Code is described below, including a description of which method(s) it can follow and any metainformation required in the response.

10.1 Informational 1xx

This class of status code indicates a provisional response, consisting only of the Status-Line and optional headers, and is terminated by an empty line. There are no required headers for this class of status code. Since HTTP/1.0 did not define any 1xx status codes, servers MUST NOT send a 1xx response to an HTTP/1.0 client except under experimental conditions.

A client MUST be prepared to accept one or more 1xx status responses prior to a regular response, even if the client does not expect a 100 (Continue) status message. Unexpected 1xx status responses MAY be ignored by a user agent.

关于Java HttpURLConnection如何接收来自服务器的多个响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4066825/

相关文章:

http - 为 future 的资源选择正确的 HTTP 返回代码

android - NSURLSession 等同于 Android?

Android Https 状态码 -1

android - 数据连接丢失时 Outputstream 上没有 IOException

java - 后台服务形状

Java多表查询

java - 在字符串中搜索一段时间。 java

java - 关闭后如何重用ThreadPoolExecutor

python - 使用 python 打印设置 header 访问控制允许来源

ASP.NET 发布 Application_Error 事件