我想使用套接字下载图像。我目前能够做到这一点,但传入的 HTTP/1.1 header 是唯一的问题。有没有一种简单的方法可以从缓冲区中排除这些 header ,以便文件内容仅包含加密图像?
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
最佳答案
你能不能用HttpURLConnection
而不是为了省去处理 HTTP 协议(protocol)的麻烦?
然后您可以自由地只处理 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
关于java - 从缓冲区中排除 HTTP/1.1 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8682799/