HttpURLConnection : 客户端和服务器如何保持同步

HttpURLConnection : How does client and server keep in sync

我正在使用 HttpURLConnection,但我对客户端和服务器如何同步有疑问。假设简单的下载文件示例。这个例子是从网上复制过来的。我只是用代码来说明标准流程。

Servlet 代码如下:

   response.setContentType(mimeType);
   response.setContentLength((int) downloadFile.length());

   String headerKey = "Content-Disposition";
   String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
   response.setHeader(headerKey, headerValue);

    // obtains response's output stream
   OutputStream outStream = response.getOutputStream();
    //write to stream
    //close the stream

客户端代码如下:

HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
    String disposition = httpConn.getHeaderField("Content-Disposition");
    String contentType = httpConn.getContentType();
    int contentLength = httpConn.getContentLength();
    //parse content-disposition
    ....
    InputStream inputStream = httpConn.getInputStream();
    String saveFilePath = saveDir + File.separator + fileName;

    // opens an output stream to save into file
    FileOutputStream outputStream = new FileOutputStream(saveFilePath);
    //write to stream
    //close stream
} else {
    //if non Ok status
}

我的第一个问题是:httConn.getResponseCode() 是等待 servlet 完成处理的阻塞调用吗?否则,如果出现错误或 servlet 调用 response.sendError(),当您在 if (responseCode == HttpURLConnection.HTTP_OK) { 内时,将会发生什么。

第二个问题:是第一个问题的延伸。如果 responseCode 没有阻塞,那么当我访问 disposition、contentType、cotentLength 时,我如何确定它们已经设置好。

第三个问题。如果 httConn.getResponseCode() 正在阻塞。因此,如果我想向客户端发送一些消息,那么将它发送给客户端作为响应 headers 是多么正确: resposnse.setHeader("my-message", "some message I want to send"); 而不是使用 response.getWriter() 写入流。所以我相信客户一定会读到的。

第四个问题:如果我在servlet 上写两个object 到流,客户端将如何区分或者它能区分吗?假设我正在使用 response.getObjectOutputStream() 编写 class object,然后我可能正在使用 writer 编写一些字符串,或者之后可能会编写一个文件。客户能否区分流中的这些不同项目,还是我必须使用多个请求。每个 object 或文件或要从流中读取的字符串一个请求。

  1. 是的,如the javadoc所示

Gets the status code from an HTTP response message. For example, in the case of the following status lines:

HTTP/1.0 200 OK
HTTP/1.0 401 Unauthorized

It will return 200 and 401 respectively. Returns -1 if no code can be discerned from the response (i.e., the response is not valid HTTP).

  1. 不适用

  2. 如果需要,您可以使用 headers,但 headers 仅限于文本且长度有限 (AFAIR)。响应 body 通常用于包含...响应 body。而 headers 通常用于元数据。

  3. 服务器和客户端必须就协议达成一致。如果协议是一个响应包含两个 object,那么客户端应该读取两个 object。我不会那样做。您最好发送一个唯一容器 object 而不是按顺序发送 2 个。 HTTP 可以用来传输任何东西,但是 JSON 或 XML 文档通常用于传输结构化数据。