Download image through sockets java

前端 未结 2 715
梦如初夏
梦如初夏 2020-12-11 22:19

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

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-11 22:53

    You need to add a \r before your \n 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\r\n");
    bw.writeBytes("Host: "+servername+":80\r\n\r\n");
    bw.flush();
    

    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
    

    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 \r\n\r\n 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("\r\n\r\n");
            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();
    

    You can also find another question like yours here: Send HTTP Request manually via socket

提交回复
热议问题