通过套接字java下载图像 [英] Download image through sockets java
问题描述
我正在尝试通过套接字从服务器下载图像.我的代码工作正常,但是当我下载图像时,大小正确但图像无法打开.我不知道我做错了什么.有什么建议吗?谢谢
I am trying to download an image from a server through sockets. My code works fine, but when I download the image, the size is correct but the image does not open. I don't know what am I doing wrong. Any suggestion? Thank you
Socket socket = new Socket(servername, 80);
DataOutputStream bw = new DataOutputStream(new DataOutputStream(socket.getOutputStream()));
bw.writeBytes("GET "+filename+" HTTP/1.1
");
bw.writeBytes("Host: "+servername+":80
");
DataInputStream in = new DataInputStream(socket.getInputStream());
OutputStream dos = new FileOutputStream("testtttt.jpg");
int count;
byte[] buffer = new byte[2048];
while ((count = in.read(buffer)) != -1)
{
dos.write(buffer, 0, count);
dos.flush();
}
dos.close();
System.out.println("image transfer done");
socket.close();
}
推荐答案
您需要在所有请求的 之前添加一个 ,另外您应该将输出流刷新到套接字.
You need to add a before your on all requests, additionally you should flush your output stream to the socket.
Socket socket = new Socket(servername, 80);
DataOutputStream bw = new DataOutputStream(socket.getOutputStream());
bw.writeBytes("GET "+filename+" HTTP/1.1
");
bw.writeBytes("Host: "+servername+":80
");
bw.flush();
此外,您将在请求中获得一些 HTTP 响应标头.显然,这是您不希望出现在图像中的信息,您的回复将如下所示:
Additionally you will get some HTTP response headers with your request. Obiously this is information you dont want in your image, your response will look something like this:
HTTP/1.1 200 OK
Date: Thu, 14 Nov 2013 18:39:47 GMT
Server: Apache/2.4.3 (Win32) OpenSSL/1.0.1c PHP/5.4.7
Accept-Ranges: bytes
ETag: W/"2956-1374616977919"
Last-Modified: Tue, 23 Jul 2013 22:02:57 GMT
Content-Type: image/png;charset=UTF-8
Content-Length: 2956
‰JPG....heres your image data
我刚刚编写了这个方法来摆脱发送的 HTTP 标头.这个想法是在 发生之前不写入任何数据.该序列代表标头响应的结束,之前的任何数据都不是我们的图像.我知道有一种更简洁的方法来做到这一点,但这种方式对我来说写起来很快:)
I just wrote up this method to get rid of the HTTP headers sent across. The idea is to not write any data before a occurrence. That sequence represents the end of the header response and any data before that is not our image. I know there is a cleaner way to do it but this way was fast for me to write :)
OutputStream dos = new FileOutputStream("c:\testtttt.jpg");
int count;
byte[] buffer = new byte[2048];
boolean eohFound = false;
while ((count = in.read(buffer)) != -1)
{
if(!eohFound){
String string = new String(buffer, 0, count);
int indexOfEOH = string.indexOf("
");
if(indexOfEOH != -1) {
count = count-indexOfEOH-4;
buffer = string.substring(indexOfEOH+4).getBytes();
eohFound = true;
} else {
count = 0;
}
}
dos.write(buffer, 0, count);
dos.flush();
}
in.close();
dos.close();
您还可以在这里找到另一个类似的问题:通过套接字手动发送 HTTP 请求
You can also find another question like yours here: Send HTTP Request manually via socket
这篇关于通过套接字java下载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!