(HttpURLConnection)url.openConnection()运行错误

上一篇 / 下一篇  2013-08-29 16:51:18 / 个人分类:step by step android测试

HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection();
运行上面的代码时出现错误:
android.os.NetworkOnMainThreadException
这个方法只在4.0以前的,4.0以后,必须在子线程中进行url的访问:
protected void urlConn(){
        new AsyncTask<Void,Void,String>(){

            @Override
            protected String doInBackground(Void... voids) {
                String content="";
                try {
                    URL url=new URL(googleWeatherUrl1);

                    HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection();
                    if(httpURLConnection.getResponseCode()==HttpURLConnection.HTTP_OK){
                       Toast.makeText(getApplicationContext(),"连接Google Weather API成功!",
                                Toast.LENGTH_LONG).show();
                        InputStreamReader inputStreamReader=
                                new InputStreamReader(httpURLConnection.getInputStream(),"utf-8");
                        int i;

                        //read
                        while (((i=inputStreamReader.read())!=-1)){
                            content=content+(char)i;
                        }
                        inputStreamReader.close();
                                            }
                    httpURLConnection.disconnect();
                } catch (Exception e) {

                    e.printStackTrace();
                }

                return content;
            }

            @Override
            protected void onPreExecute() {

                super.onPreExecute();
            }

            @Override
            protected void onPostExecute(String content) {
                super.onPostExecute(content);


            }
        }.execute();
}
如果你看了链接中的文章的话,会发现上面代码中TOAST方法会导致错误,Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()。我们需要将与网络连接无关的代码移出这个线程之外。

TAG:

 

评分:0

我来说两句

Open Toolbar