URL and FileNotFoundException


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();
}
}
}
 
Ad

Advertisements

S

Sudsy

Ryan Stewart wrote:
public void work() throws MalformedURLException, IOException {
URL url = new URL("http://localhost:" + port + "/blah.jsp");
System.out.println("** Requesting " + url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if( conn.getResponseCode() != HttpURLConnection.HTTP_OK ) {
// process error
return;
}
InputStream in = conn.getInputStream();
int data;
while ((data = in.read()) != -1) {
System.out.print((char) data);
}
in.close();
}
<snip>
 
Ad

Advertisements

R

Ryan Stewart

Sudsy said:
Ryan Stewart wrote:

HttpURLConnection conn = (HttpURLConnection)
url.openConnection();
if( conn.getResponseCode() != HttpURLConnection.HTTP_OK ) {
// process error
return;
}
InputStream in = conn.getInputStream();
<snip>
Thanks a bunch. I see how it works now. That's also handy for catching
redirects.
 

Top