0

I am writing an app on android 3.1, and I am using galaxy tab 10.1 to test my app.

I wrote a function called OpenHttpConnection() in order to get some information from a specific website. And the code snippets is:

private InputStream OpenHttpConnection(String urlString) throws IOException {
    InputStream in = null;
    int response = -1;

    URL url = new URL(urlString);
    String host = url.getHost();
    InetAddress address = InetAddress.getByName(host);
    String ip = address.getHostAddress();
    Toast.makeText(this, "ip address: " + ip.toString(), Toast.LENGTH_SHORT).show();

    try {
        HttpURLConnection httpConn = (HttpURLConnection)url.openConnection();
        httpConn.setAllowUserInteraction(false);
        httpConn.setInstanceFollowRedirects(true);
        httpConn.setConnectTimeout(5 * 1000);
        httpConn.setRequestMethod("GET");
        Toast.makeText(this, "prepare for connecting", Toast.LENGTH_SHORT).show();
        httpConn.connect();
        Toast.makeText(this, "connecting established", Toast.LENGTH_SHORT).show();
        response = httpConn.getResponseCode();
        if (response == HttpURLConnection.HTTP_OK) {
            in = httpConn.getInputStream();
        }
    } catch (Exception ex) {
        throw new IOException("Error connecting");
    }
    return in;
}

Error happens when the line "httpConn.connect()" is being executed. I googled this question and found many people got this problem, and they said it was a matter of DNS. Then I tried to get the ip address of this url, I failed, somethings was wrong. I have already add the permission to the AndroidManifest.xml like this:

<uses-permission android:name="android.permission.INTERNET"/>

Did I miss some permission?

I can use my tablet to access the internet successfully and the DNS of my tablet is as same as my pc, and they are in one LAN.

I am very confused, and can u help solve it?

;)thx

4

1 回答 1

0

我最近一直在这样做,所以我可能会告诉你有两个可能的问题:

  1. 您需要确保在后台线程上使用HandlerAsyncTask.

  2. 如果必须在 UI 线程中执行此操作,则需要关闭Strict mode.

查看这个在 android 中运行后台线程的精彩教程,教程的 AyncTask 部分实际上下载了一个网页,因此非常相关。我最近尝试过它并且它有效。

于 2012-04-08T09:50:34.437 回答