Android连接到网络示例给我IOException

时间:2014-05-11 12:17:16

标签: android android-asynctask

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

我想实现类似这样的东西,以便我的Android应用程序可以连接到php webservice以从网页获得结果。

这里的问题是方法" 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);
    }       

} 

1 个答案:

答案 0 :(得分:0)

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

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

通过将URL打印到日志中来检查URL是否格式正确。 具体是&#34; strDatabaseWebService +&#34; checkmemberexists.php?email =&#34; + email&#34;决心。

此外,如果您可以发布日志,可能有助于查看出现了什么问题。

编辑:

我在&#34; doInBackground()&#34;中使用与此类似的代码。开发此问题时遇到的问题与HttpURLConnection实现有关。当&#34; keepalive&#34;显然有一些问题需要重用连接。活跃。在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;
    }
}