如何使用套接字下载图像

时间:2018-08-01 22:52:31

标签: java image sockets

所以我正在练习使用套接字从Web获取图像。我不确定在存储图像字节然后创建文件时要使用哪个类。到目前为止,我的代码是:

    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\r\n\r\n";
            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 个答案:

答案 0 :(得分:0)

我修复了您的代码。它将所有数据保存到文件。

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\r\n\r\n";
    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响应。这就是使用套接字而不使用HTTP感知类库(例如Apache HttpClient)所获得的。您可以使用任何文本编辑器打开文件以查看内容。

enter image description here

如果您确实确定要继续使用套接字,请咨询可能的duplicate linked by gtgaxiola。它包含更多代码以应对将标头与实际数据分离的问题。