3

そこで、Web サイトにリクエストを送信するための小さなメソッドを作成し、それがクラッシュしないようにしたいと考えました。インターネットを切断してメソッドを呼び出すと、java.net.UnknownHostException:が表示されますが、キャッチできません。私は何を間違っていますか?

問題のatmを提供している行はHttpResponse response = httpclient.execute(httppost);

IO の前に ClientProtocolException (IO のサブクラス) も処理するので、両方の catch ブロックを使用できます。throws clausesハイレベル用にも追加してみましたException e。これが私のコードです:

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

1 に答える 1

0

確かに、この質問は閉じられるべきです。なんで?

問題のソースを確認しました。

あなたの最後のバージョンのクラスConnectionはコンパイルすることさえ望んでいません。Javaはステートメントに文句を言いreturn empty;ます。この変数は何emptyですか?

(例)に変更return empty;しても、return answer;すべてうまくいきます。

たとえば、に接続しようとするとhttp://www.fdsfsaddsfsddsafasd.com、最後のステートメントjava.net.UnknownHostExceptionで正常にキャッチされます。...catch(IOException ...

プロジェクトを完全に再構築し、デバッグモードで実行して、もう一度テストを実行することをお勧めします。

于 2013-01-29T11:10:54.753 に答える