IOException未捕获java.net.UnknownHostException异常:

3

于是我创建了一个小方法来发送请求到网站,并且我想要确保它不会崩溃。当我断开互联网并调用该方法时,我会得到一个 java.net.UnknownHostException:,但我无法捕获它。我做错了什么?

目前出现问题的行是 HttpResponse response = httpclient.execute(httppost);

我甚至在IO异常之前处理了ClientProtocolException(IO的子类),这样我就可以有两个catch块了。我还尝试过为高级别的 Exception e 添加throws从句。以下是我的代码:

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;
    }
}

还有一个例外:

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)

可运行的代码:

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;
    } 
}

1
哪一行代码出错了? - SJuan76
7
你确定这个堆栈跟踪不是由你在catch块中的Logger.log()调用打印出来的吗? - JB Nizet
1
我能想到的唯一原因是你运行的不是这段代码,而是之前编译好的版本。为了解决这个问题,建议你在方法的开头添加 System.out.println("Hello world!") 并重新运行代码,这样可以更容易地检查已编译的类是否与代码匹配。虽然这种情况可能性较小,但除此之外我无法想到其他可能导致这个问题的原因。 - SJuan76
1
我认为@JBNizet是正确的。您可以通过将代码编辑为Logger.getLogger(Connection.class.getName()).log(Level.SEVERE, "Exception caught:", ex);并查看输出来验证它。 - jlordo
2
这是 poltergeist... 你能贴出当前的 Connection.java 吗?如果你无法捕获 IOException... 就看不到你在哪里打印了 printStacktrace ;-) - ggrandes
显示剩余8条评论
1个回答

0

我确信这个问题应该被关闭。为什么呢?

我刚刚检查了你在问题中提供的源代码。

你最后一版的 Connection 类甚至不能编译。Java 抱怨语句 return empty;,这个变量 empty 是什么意思?

好的,即使将 return empty; 改成 return answer;(例如) - 一切都能正常工作。

例如,如果我尝试连接到 http://www.fdsfsaddsfsddsafasd.com,那么最后一个 ...catch(IOException ... 语句会成功捕获 java.net.UnknownHostException

我建议您完全重建您的项目,并以调试模式运行它,再次进行测试。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接