从缓冲区中排除HTTP / 1.1标头

时间:2011-12-30 18:41:30

标签: java http sockets

我想使用socket下载图像。我目前能够这样做,但传入的HTTP / 1.1标头是唯一的问题。有没有一种简单的方法可以从缓冲区中排除这些标题,以便文件内容只包含加密图像?

void readImage() throws IOException
{
    socket = new Socket("wlab.cs.bilkent.edu.tr", 80);

    DataOutputStream bw = new DataOutputStream(new DataOutputStream(socket.getOutputStream()));
    bw.writeBytes("GET /~alper/pa2/images/ref2.jpg HTTP/1.1\n");
    bw.writeBytes("Host: wlab.cs.bilkent.edu.tr:80\n\n");

    File file = new File("img20.jpg");
    file.createNewFile();

    FileOutputStream fos = new FileOutputStream(file);

    DataInputStream in = new DataInputStream(socket.getInputStream());
    DataOutputStream dos = new DataOutputStream(fos);

    int count;

    byte[] buffer = new byte[8192];
    while ((count = in.read(buffer)) > 0)
    {
      dos.write(buffer, 0, count);
      dos.flush();
    }
    dos.close(); 

    System.out.println("image transfer done");
    socket.close();     
}

下载的图片顶部包含以下行:

HTTP/1.1 200 OK
Date: Fri, 30 Dec 2011 18:30:50 GMT
Server: Apache/2.2.3 (Debian) mod_jk/1.2.18 mod_python/3.2.10 Python/2.4.4 PHP/5.2.0-8+etch4 mod_ssl/2.2.3 OpenSSL/0.9.8c mod_perl/2.0.2 Perl/v5.8.8
Last-Modified: Tue, 20 Dec 2011 19:12:23 GMT
ETag: "502811-6b0e-4b48ad8d273c0"
Accept-Ranges: bytes
Content-Length: 27406
Content-Type: image/jpeg

2 个答案:

答案 0 :(得分:2)

您是否可以不使用HttpURLConnection来节省处理HTTP协议的麻烦?

然后,您可以自由处理HTTP消息正文中的数据。

但@Skip Head是对的,标题以CRLF结尾。请参阅HTTP规范中的以下内容。

http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html

    generic-message = start-line
                      *(message-header CRLF)
                      CRLF
                      [ message-body ]
    start-line      = Request-Line | Status-Line

答案 1 :(得分:0)

标题以空白行结束。