CN Lab-6

// Socket programming to download image from web

import java.net.*;

import java.io.*;

public class WebClientImage

{

public static void main(String[] args) throws Exception

{

//open a socket to the URL www.java2s.com"

InetAddress IPobject=InetAddress.getByName("www.bits-pilani.ac.in");

Socket Fromclient= new Socket(IPobject,80);

PrintWriter OutToServer= new PrintWriter(Fromclient.getOutputStream());

OutToServer.println("GET //Uploads/Campus/BITS_Dubai_campus_logo.gif HTTP/1.1");

OutToServer.println("Host: www.bits-.pilani.ac.in");

OutToServer.println("");//send a blank line

OutToServer.flush();//do not forget

InputStream InputFromServ= Fromclient.getInputStream();// attach an inputstream to socket

File Fileobj= new File("C:\\Users\\test\\Downloads\\Image.gif");

FileOutputStream OutToFile= new FileOutputStream(Fileobj);

byte[] ImageBytes= new byte[2048];

//read block of data via inputstream and put it into the defined byte array

int length;

boolean HeadersComplete=false;

while((length=InputFromServ.read(ImageBytes))!=-1)

{

if(HeadersComplete)// already got rid of all the headers

{

OutToFile.write(ImageBytes,0,length);//for further image data from server

//after /r/n/r/n detected

}

else// still yet to get rid of end of headers

{

for(int i=0;i< 2045;i++)

{

if(ImageBytes[i]==13 && ImageBytes[i+1]==10 && ImageBytes[i+2]==13 && ImageBytes[i+3]==10)

{

HeadersComplete=true;

OutToFile.write(ImageBytes,i+4,2048-i-4);

break;// first time end of headers detected

}

}//end of for loop

}// end of else

//OutToFile.write(ImageBytes,0,length);

}// end of while

OutToFile.flush();//flush the fileoutputstream to push all information

// Fileobj.close();

}

}

WRITE A PROGRAM TO DOWNLOAD THE IMAGE OF YOUR FAVORITE CARTOON CHARACTER USING HTTPURLCONNECTION OBJECT CLASS IN JAVA.NET PACKAGE

In Java, we can use the classes URL and HttpURLConnection in the package java.net to programmatically download a file from a given URL by following these steps:

    • Create a URL object for a given URL. The URL can be either:
      • A direct link which contains the real file name at the end, for example:

http://jdbc.postgresql.org/download/postgresql-9.2-1002.jdbc4.jar

      • An indirect link which does not contain the real file name, for example:

http://myserver.com/download?id=1234

    • Open connection on the URL object – which would return an HttpURLConnection object if the URL is an HTTP URL.
    • Open the input stream of the opened connection.
    • Create an output stream to save file to disk.
    • Repeatedly read array of bytes from the input stream and write them to the output stream, until the input stream is empty.
    • Close the input stream, the output stream and the connection.

For the purpose of reusability, we create a utility class as follows:

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.URL;

/**
 * A utility that downloads a file from a URL.
 * @author www.codejava.net
 *
 */

public class HttpDownloadUtility {

private static final int BUFFER_SIZE = 4096;

    /**
     * Downloads a file from a URL
     * @param fileURL HTTP URL of the file to be downloaded
     * @param saveDir path of the directory to save the file
     * @throws IOException
     */

public static void downloadFile(String fileURL, String saveDir)

throws IOException {

URL url = new URL(fileURL);

        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();

int responseCode = httpConn.getResponseCode();

        // always check HTTP response code first

if (responseCode == HttpURLConnection.HTTP_OK) {

            String fileName = "";
            String disposition = httpConn.getHeaderField("Content-Disposition");
            String contentType = httpConn.getContentType();

int contentLength = httpConn.getContentLength();

if (disposition != null) {

                // extracts file name from header field

int index = disposition.indexOf("filename=");

if (index > 0) {

                    fileName = disposition.substring(index + 10,
                            disposition.length() - 1);
                }

} else {

                // extracts file name from URL
                fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
                        fileURL.length());
            }

System.out.println("Content-Type = " + contentType);

System.out.println("Content-Disposition = " + disposition);

System.out.println("Content-Length = " + contentLength);

System.out.println("fileName = " + fileName);

            // opens input stream from the HTTP connection
            InputStream inputStream = httpConn.getInputStream();
            String saveFilePath = saveDir + File.separator + fileName;

            // opens an output stream to save into file

FileOutputStream outputStream = new FileOutputStream(saveFilePath);

int bytesRead = -1;

byte[] buffer = new byte[BUFFER_SIZE];

while ((bytesRead = inputStream.read(buffer)) != -1) {

                outputStream.write(buffer, 0, bytesRead);
            }

            outputStream.close();
            inputStream.close();

            System.out.println("File downloaded");

} else {

System.out.println("No file to download. Server replied HTTP code: " + responseCode);

        }
        httpConn.disconnect();
    }
}