我正在做一个从网站获取图片的项目(任何人都可以),并且我知道我可以使用 URL 来获取它。但我想更好地了解 TCP,所以我使用套接字来获取它。一切都可以,但问题是我收到的数据流包含 HTTP 的响应,我不知道如何过滤它。 这是我的代码(只是其中的一部分)
Socket socket = new Socket(netAdress, 80);
bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bw.write("GET HTTP://" + sources + " HTTP/1.0\r\n");
bw.write("\r\n");
bw.flush()//connect
BufferedOutputStream writeImg = new BufferedOutputStream(new FileOutputStream(adj));
byte[] data = new byte[512];
int len=0;
boolean OK=false;
while ((len=in.read(data))>0) {
writeImg.write(data,0,len);
writeImg.flush();
}//receive the data stream
这是我收到的,图片打不开。 the detail of the data stream
如果您知道如何解决问题或者您有更好的想法通过套接字获取图片,请与我联系。谢谢。
最佳答案
... this is what I received,and the picture couldn't open
是的。响应以 HTTP 响应 header 开始。
If you know how to solved the problem ...
嗯,这是一个 hack,不推荐(并且一般情况下它不起作用!),但是 HTTP 响应 header 以第一个 <CR> <NL> <CR> <NL>
结尾。序列(ASCII 控制代码)。因此,如果您去掉该序列之前的所有内容(包括该序列),您应该会得到一个图像。 (除非是压缩的,或者编码的,或者多部分的,或者......)
... or you have a better idea of get the picture.
更好的主意是使用 URL。说真的。
关于java - Java使用socket从网页获取图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34389113/