【问题标题】:Android device is unable to connect to webpage with HttpURLConnectionAndroid 设备无法使用 HttpURLConnection 连接到网页
【发布时间】:2013-04-11 19:10:50
【问题描述】:

我正在开发一个 android 应用程序,它会从网页中获取源代码,然后对其进行解析。

只要我的设备连接到开发它的电脑,我就能让它工作,但是,当我尝试在与电脑断开连接的情况下运行它时,它似乎无法检索信息。有人可以告诉我我做错了什么吗?

为了获取源代码,我通过 AsyncTask 使用以下代码:

private String downloadUrl(String myurl) throws IOException {
    InputStream is = null;

    try {
        URL url                 = new URL(myurl);
        HttpURLConnection conn  = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(20000 /* milliseconds */);
        conn.setConnectTimeout(25000 /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);

        // Starts the query
        conn.connect();
        response = conn.getResponseCode();
        Log.d(DEBUG_TAG, "The response is: " + response);

        if (response == 200) {

            is = conn.getInputStream();

            BufferedReader buffer = new BufferedReader(new InputStreamReader(is, "ISO-8859-1"));

            // Convert the InputStream into a string
            String s = "";
            while ((s = buffer.readLine()) != null) {
                myTextView.append(s);
                myTextView.append("\n");

            }

            conn.disconnect();
            is.close();
            return myTextView.getText().toString();
        } else {
            conn.disconnect();
            return "";
        }


    } finally {
        if (is != null) {
            is.close();

        } 
    }
}

【问题讨论】:

  • 不知道它是否会有所帮助,但是一旦您致电openConnection(),您就不必致电connect()
  • @Haelty 我需要像以前那样关闭连接吗?我也尝试在发布模式下运行它,但是手机无法建立连接。
  • 是的,最好关闭连接;)但是您可以在finally 块中调用它,以便在任何情况下都会调用它(即使之前调用了return)。
  • @Haelty 不,我不能,因为 conn 是在 try 块中定义的
  • 你是对的。所以保持原样。但是会发生什么?它会抛出异常还是返回空字符串?响应码是什么?

标签: android android-asynctask httpurlconnection


【解决方案1】:

似乎在我对 ASyncTask 的调用中,以下行让设备等待计算机连接。

android.os.Debug.waitForDebugger();

【讨论】:

  • 这样称呼有什么意义?在调试模式下,应用程序还没有等待调试器? :P
  • 不,它不会在 AsyncTask 调用的代码中停止,因为它位于不同的线程上,请参阅 this answer
猜你喜欢
  • 2012-12-22
  • 2013-10-30
  • 1970-01-01
  • 1970-01-01
  • 2022-01-16
  • 2016-08-18
  • 1970-01-01
  • 2022-11-06
  • 1970-01-01
相关资源
最近更新 更多