【问题标题】:Android Connecting to Network Example gives me IOExceptionAndroid 连接到网络示例给了我 IOException
【发布时间】:2014-05-11 12:17:16
【问题描述】:

我试图实现连接到 http 客户端以接收数据的 Android 示例。 http://developer.android.com/training/basics/network-ops/connecting.html

我想实现这样的东西,以便我的 Android 应用可以连接到 php 网络服务以从网页中获取结果。

这里的问题是方法“checkMemberExists(urls[0])”一直给我一个 IOException,因此程序退出并且没有进入 onPostExecute(..)。 我试图实现与上述链接中的示例接近。但不明白为什么它对我不起作用。任何帮助将不胜感激。

private class DbCheckMemberExistsTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... urls) {

        // params comes from the execute() call: params[0] is the url.
        try {

            String strContentString = checkMemberExists(urls[0]);

            return strContentString;

        } catch (IOException e) {
            return "Unable to retrieve web page. URL may be invalid.";
        }
    }
    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {
        memberExists.setText(result);
   }


    public String checkMemberExists(String email) throws IOException 
    {

        //returns 0 : does not exists
        //returns 1 : exists but not activated
        //returns 2 : exists and activated

        InputStream is = null;
        int len = 500;

        try
        {
            URL url = new URL(strDatabaseWebService+"checkmemberexists.php?email="+email);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);

            conn.connect();
            int response = conn.getResponseCode();
            Log.d("log_debug", "The response is: " + response);
            is = conn.getInputStream();

            // Convert the InputStream into a string
            String contentAsString = readIt(is, len);
            Log.d("log_debug", "The response is: " + contentAsString);




            //return contentAsString;
            return contentAsString;

        }
        catch (IOException e)
        {
            return "9";
        }
        finally 
        {
            if (is != null) {
                is.close();
            }           
        }   

    }

    // Reads an InputStream and converts it to a String.
    public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
        Reader reader = null;
        reader = new InputStreamReader(stream, "UTF-8");        
        char[] buffer = new char[len];
        reader.read(buffer);
        return new String(buffer);
    }       

} 

【问题讨论】:

标签: android android-asynctask


【解决方案1】:

检查清单中是否有互联网权限:

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

通过将 URL 打印到日志中来检查 URL 的格式是否正确。 具体来说“strDatabaseWebService+”checkmemberexists.php?email="+email" 解析为什么。

此外,如果您可以发布您的日志,这可能有助于了解问题所在。

编辑:

我在“doInBackground()”中使用了与此类似的代码。我在开发时遇到的问题与 HttpURLConnection 实现有关。显然,当“keepalive”处于活动状态时,重用连接存在一些问题。 SO中有很多关于这个的帖子。 您可以尝试看看这是否能帮助您解决问题。

    try{
        //(1) This has to do with something not working properly in the HttpURLConnection class and how it reuses connections
        //So the advice is to close each connection after using it.
        System.setProperty("http.keepAlive", "false");
        URL url;
        url = new URL("http://stackoverflow.com/questions/23592510/android-connecting-to-network-example-gives-me-ioexception/23592876?noredirect=1#comment36228428_23592876");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setUseCaches(false);
        conn.setConnectTimeout(20000);
        //(2) The seme as (1)
        conn.setRequestProperty("Connection", "close");
        conn.connect();
        InputStream is = new BufferedInputStream(conn.getInputStream());

        //(3) Dirty workaround when reading a lot of files one after another, I randomly get some strange values.
        //You can try not using the "sleep", but I thougt of including it because I understood you read many files one after another one.
        try{
            Thread.sleep(200);
        }catch (InterruptedException e) {
            // Ignore this, not a big deal
        }

        StringBuffer sb = new StringBuffer();
        int c = is.read();
        while (c!= -1){
            sb.append((char) c);
            c = is.read();
        }

        is.close();
        conn.disconnect();
        return sb.toString();
    }catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

【讨论】:

  • 谢谢。我已将用户权限放在 android 清单中。此外,URL 是正确的,因为我可以将数据提取到 InputStream 并在 IDE 中查看数据。还是同样的问题。感谢您的帮助。
猜你喜欢
  • 2015-10-29
  • 2011-08-11
  • 1970-01-01
  • 2013-08-03
  • 2017-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多