R
Ryan Stewart
I haven't worked much with URLs and such. The following code works almost as
desired. The only problem is that if "blah.jsp" doesn't exist on
http://localhost:<port>/, it throws a FileNotFoundException. If I request an
existing resource, it returns the resource just fine (though I somewhat
expected to get the HTTP headers as well). For a non-existing resource, I
was looking for it to return the HTML of the server's 404 page. Essentially,
I want this program to act as a mini-browser and always return the server's
response, not throw exceptions like this. Should I just make a straight
Socket connection to the server and read back the full response manually?
import java.io.*;
import java.net.*;
public class URLTester {
public static final int TEST_PORT = 8080;
private int port;
public URLTester(int port) {
this.port = port;
}
public void work() throws MalformedURLException, IOException {
URL url = new URL("http://localhost:" + port + "/blah.jsp");
System.out.println("** Requesting " + url);
InputStream in = url.openStream();
int data;
while ((data = in.read()) != -1) {
System.out.print((char) data);
}
in.close();
}
public static void main(String[] args) {
URLTester tester = new URLTester(TEST_PORT);
try {
tester.work();
} catch (MalformedURLException mue) {
mue.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
desired. The only problem is that if "blah.jsp" doesn't exist on
http://localhost:<port>/, it throws a FileNotFoundException. If I request an
existing resource, it returns the resource just fine (though I somewhat
expected to get the HTTP headers as well). For a non-existing resource, I
was looking for it to return the HTML of the server's 404 page. Essentially,
I want this program to act as a mini-browser and always return the server's
response, not throw exceptions like this. Should I just make a straight
Socket connection to the server and read back the full response manually?
import java.io.*;
import java.net.*;
public class URLTester {
public static final int TEST_PORT = 8080;
private int port;
public URLTester(int port) {
this.port = port;
}
public void work() throws MalformedURLException, IOException {
URL url = new URL("http://localhost:" + port + "/blah.jsp");
System.out.println("** Requesting " + url);
InputStream in = url.openStream();
int data;
while ((data = in.read()) != -1) {
System.out.print((char) data);
}
in.close();
}
public static void main(String[] args) {
URLTester tester = new URLTester(TEST_PORT);
try {
tester.work();
} catch (MalformedURLException mue) {
mue.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}