How to download an image with Sockets
本问题已经有最佳答案,请猛点这里访问。
所以我正在做一个练习,用套接字从网络上获取图像。我不确定在存储图像字节然后创建文件时要使用哪个类。到目前为止,我的代码是:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | import java.io.*; import java.net.*; import java.awt.image.*; import javax.imageio.stream.ImageInputStream; import javax.imageio.ImageIO; class MyClass{ public static void main(String[] args)throws IOException{ Socket s = new Socket(); ImageInputStream s_in = null; //I'm not sure about this PrintWriter s_out = null; try{ s.connect(new InetSocketAddress("data.pr4e.org",80)); System.out.println("Connected"); s_out = new PrintWriter(s.getOutputStream(), true); s_in = ImageIO.createImageInputStream(s.getInputStream());//nor this } catch (UnknownHostException e){ System.err.println("Don't know about host"); System.exit(1); } //Message to server String message ="GET http://data.pr4e.org/cover3.jpg HTTP/1.0 "; s_out.println(message); //This is where it gets confusing OutputStream out = null; while (true){ try{ out = new BufferedOutputStream(new FileOutputStream("C:\\Users\\Steff\\Desktop\\Java ejemplos\\cover3.jpg")); out.write(s_in.read()); } finally{ if(out != null){ out.close(); } } } } |
}
我修正了你的代码。它将所有数据保存到文件中。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | public static void main(String[] args) throws IOException { Socket s = new Socket(); InputStream s_in = null; PrintWriter s_out = null; try { s.connect(new InetSocketAddress("data.pr4e.org", 80)); System.out.println("Connected"); s_out = new PrintWriter(s.getOutputStream(), true); s_in = s.getInputStream(); } catch (UnknownHostException e) { System.err.println("Don't know about host"); System.exit(1); } // Message to server String message ="GET http://data.pr4e.org/cover3.jpg HTTP/1.0 "; s_out.println(message); OutputStream out = new BufferedOutputStream(new FileOutputStream("C:\\Users\\Steff\\Desktop\\Java ejemplos\\cover3.jpg")); int count; byte[] buffer = new byte[4096]; while ((count = s_in.read(buffer)) > 0) { out.write(buffer, 0, count); } out.close(); } |
不幸的是,图像不可读。为什么?因为保存的数据包含整个流以及HTTP响应。这就是在不使用诸如ApacheHTTPClient之类的HTTP感知库的情况下使用套接字所得到的。您可以使用任何文本编辑器打开文件以查看内容。
。
如果您真的确定要继续使用套接字,请参考GTGAXIOLA链接的可能副本。它包含更多的代码来处理从实际数据中分离头的问题。