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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top