3

So I created a small method to send a request to a website, and I wanted to make sure it didn't crash. When I disconnect the internet and call the method, I get a java.net.UnknownHostException:, but I am not able to catch it. What am I doing wrong?

The line that is giving issues atm is HttpResponse response = httpclient.execute(httppost);

I even handle the ClientProtocolException (subclass of IO) before the IO, so I could have both catch blocks. I've also tried adding throws clauses for the high level Exception e. Here is my code:

public String connect(String username, String password) {
    String answer = "Could not connect to server, please check your internet connect or try later.";
    try {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(baseurl);
        // Request parameters and other properties.
        List<NameValuePair> params = new ArrayList<NameValuePair>(2);
        params.add(new BasicNameValuePair("usernameUS", username));
        params.add(new BasicNameValuePair("passwordUS", password));
        httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

        // Execute and get the response.
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            answer = EntityUtils.toString(entity, charset);
            try {
                if (answer.equals("Authenticated")) {
                    this.password = password;
                    this.username = username;
                    Authenticated = true;
                    return answer;
                } else {
                    return answer;
                }
            } finally {
            }
        }
        return "Could not connect to server, please try later.";
    } catch (ClientProtocolException ex) {
        Logger.getLogger(Connection.class.getName()).log(Level.SEVERE,
                null, ex);
        return answer;
    } catch (IOException ex) {
        Logger.getLogger(Connection.class.getName()).log(Level.SEVERE,
                null, ex);
        return answer;
    }
}

And the exception:

java.net.UnknownHostException: www.example.com
    at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
    at java.net.InetAddress$1.lookupAllHostAddr(InetAddress.java:866)
    at java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1258)
    at java.net.InetAddress.getAllByName0(InetAddress.java:1211)
    at java.net.InetAddress.getAllByName(InetAddress.java:1127)
    at java.net.InetAddress.getAllByName(InetAddress.java:1063)
    at org.apache.http.impl.conn.SystemDefaultDnsResolver.resolve(SystemDefaultDnsResolver.java:45)
    at org.apache.http.impl.conn.DefaultClientConnectionOperator.resolveHostname(DefaultClientConnectionOperator.java:278)
    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:162)
    at org.apache.http.impl.conn.ManagedClientConnectionImpl.open(ManagedClientConnectionImpl.java:294)
    at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:640)
    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:479)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:805)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:784)
    at usclient.Connection.connect(Connection.java:65)

Working code:

public class Connection {
private static Connection conn;
String username, fileURL;
String baseurl = "http://www.example.com";
String content, password = "";
String charset = "UTF-8";
HttpURLConnection request;
URL url;
OutputStreamWriter post;
BufferedReader in;

private Connection()    {
}

public static Connection getInstance()  {
    if(conn==null)  {
        conn = new Connection();
    }
    return conn;
}

public String connect(String username, String password){
    String answer = "Could not connect to server, please check your internet connect or try later.";
    try {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(baseurl);
        // Request parameters and other properties.
        List<NameValuePair> params = new ArrayList<NameValuePair>(2);
        params.add(new BasicNameValuePair("usernameUS", username));
        params.add(new BasicNameValuePair("passwordUS", password));
        httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

        //Execute and get the response.
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            String[] data = EntityUtils.toString(entity, charset).split("\\n");
            answer = data[0];
            try {
                if(answer.contentEquals("Authenticated")) {
                    this.password = password;
                    this.username = username;
                    if(data.length<1)
                        fileURL = data[1];
                    return data[0];
                }
                else {
                    return answer;
                }
            } finally {
            }
        }
        return "Could not connect to server, please try later.";
    } catch (ClientProtocolException ex) {
        Logger.getLogger(Connection.class.getName()).log(Level.SEVERE, "Exception caught:", ex);
        return empty;
    } catch (IOException ex) {
        Logger.getLogger(Connection.class.getName()).log(Level.SEVERE, "Exception caught:", ex);
        return empty;
    } 
}
Juan
  • 521
  • 1
  • 11
  • 28
  • 1
    which line is throwing it? – SJuan76 Jan 05 '13 at 13:47
  • Will add on question too, sorry. HttpResponse response = httpclient.execute(httppost); – Juan Jan 05 '13 at 13:49
  • 7
    Are you sure this stack trace isn't printed by your Logger.log() call in the catch block? – JB Nizet Jan 05 '13 at 13:51
  • 1
    The only reason that I can think of is because you are not running this code but a previously compiled version. To weed that off, I would add a `System.out.println("Hello world!")` at the beginning of the method and run it again, that will make easier to check if the compiled class matches the code. I know it is unlikely, but other than that I cannot see what can be causing this. – SJuan76 Jan 05 '13 at 13:54
  • 1
    I think @JBNizet is right. You can verify it by editing your code to `Logger.getLogger(Connection.class.getName()).log(Level.SEVERE, "Exception caught:", ex);` and look at the output afterwards. – jlordo Jan 05 '13 at 14:10
  • I added the Hello world at the start, and the problem still there + hello world. I changed both Logger lines, and still get the same result. If you want me to post the output let me know. – Juan Jan 05 '13 at 15:18
  • Wich jar for http support do you use? I have tried it shortly with gwt-dev-2.4.0-rc1.jar so a similiar error will be occurs if the baseurl is missing the protocol. Please check the urls for trivial errors for example missing protocol, missing slash, extra slash and so on (its only a speculation and a hint of me). – Huluvu424242 Jan 06 '13 at 00:04
  • So the URL works when I do not disconnect my computer from the internet, but I am checking what would happen if someone runs the program and connection is down. – Juan Jan 06 '13 at 01:02
  • 2
    This is poltergeist... can paste the current full Connection.java? if you can't catch IOException... can't see where you made the printStacktrace ;-) – ggrandes Jan 06 '13 at 07:31
  • Seems to be that JB Nizet or SJuan76 was right, so if you want to write an answer so I can give you a check. – Juan Jan 06 '13 at 09:13
  • @Juan: what's the reason for the `try` block without any `catch`es and with an empty `finally` block? – Arjan Jan 06 '13 at 14:50
  • That part of the code comes from this example, and since I was not using the content (until now) it was empty. http://stackoverflow.com/questions/3324717/sending-http-post-request-in-java – Juan Jan 06 '13 at 14:58
  • Im having the same issue. Cant Catch UnknownHostException – Zapnologica May 25 '15 at 18:22

1 Answers1

0

I'm sure, that this question should be closed. Why?

I just checked the sources, which you have provided in question.

Your last version of class Connection even doesn't want to compile. Java complains to statements return empty;. What is this variable empty?

Ok, even if change return empty; to return answer; (e.g.) - everything works well.

If, for example, I try to connect to http://www.fdsfsaddsfsddsafasd.com, then java.net.UnknownHostException is successfully caught in last ...catch(IOException ... statement.

I suggest you to fully rebuild your project, run it in debug mode and do the test once again.

Andremoniy
  • 34,031
  • 20
  • 135
  • 241