The Hypertext Transfer Protocol (HTTP) is the foundation protocol of the World W
ID: 3583729 • Letter: T
Question
Explanation / Answer
Following Java Client program for reading the content from any website whose URL name is passed as command line argument. Name of the Program is ClientGetData.java which calls the readUrl function in main method to print the contenet from website.
//ClientGetData.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
public class ClientGetData
{
public static void main(String[] args) {
url=args[1]; // we assume that user passes the url is passed as command line argument
System.out.println(" Output: " + readURL("http://"+url));
}
public static String readURL(String URLpassed) {
System.out.println("Requeted URL:" + URLpassed);
StringBuilder sb = new StringBuilder();
URLConnection urlConn = null; //url Connection Object
InputStreamReader in = null; // Input Stream Reader Object
try {
URL url = new URL(URLpassed); //instatiation of URL Object
urlConn = url.openConnection(); // instatiation of URLConnection Object
if (urlConn != null)
urlConn.setReadTimeout(60 * 1000);
if (urlConn != null && urlConn.getInputStream() != null) {
in = new InputStreamReader(urlConn.getInputStream(),
Charset.defaultCharset());
BufferedReader bufferedReader = new BufferedReader(in);
if (bufferedReader != null) {
int cp;
while ((cp = bufferedReader.read()) != -1) {
sb.append((char) cp);
}
bufferedReader.close();
}
}
in.close();
} catch (Exception e) {
throw new RuntimeException("Exception while calling URL:"+ URLpassed, e);
}
return sb.toString();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.