Download WWW Page
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;
class Main{
public String downloadWWWPage(URL pageURL) throws Exception {
String host, file;
host = pageURL.getHost();
file = pageURL.getFile();
InputStream pageStream = getWWWPageStream(host, file);
if (pageStream == null) {
return "";
}
DataInputStream in = new DataInputStream(pageStream);
StringBuffer pageBuffer = new StringBuffer();
String line;
while ((line = in.readUTF()) != null) {
pageBuffer.append(line);
}
in.close();
return pageBuffer.toString();
}
public InputStream getWWWPageStream(String host, String file) throws IOException,
UnknownHostException {
InetAddress webServer = InetAddress.getByName(host);
Socket httpPipe = new Socket(webServer, 80);
if (httpPipe == null) {
System.out.println("Socket to Web server creation failed.");
return null;
}
InputStream inn = httpPipe.getInputStream(); // get raw streams
OutputStream outt = httpPipe.getOutputStream();
DataInputStream in = new DataInputStream(inn); // turn into higher-level ones
PrintStream out = new PrintStream(outt);
if (inn == null || outt == null) {
System.out.println("Failed to open streams to socket.");
return null;
}
out.println("GET " + file + " HTTP/1.0\n");
String response;
while ((response = in.readUTF()).length() > 0) {
System.out.println(response);
}
return in;
}
}
Related examples in the same category