现在的位置: 首页 > 综合 > 正文

在线程中实现请求网络服务,抛出了IOException异常。

2018年04月04日 ⁄ 综合 ⁄ 共 1271字 ⁄ 字号 评论关闭

具体代码如下:

 Thread newThread = new Thread(new Runnable() {
            String strResult = null;
            @Override
            public void run() {
                
                // TODO Auto-generated method stub
                 // 利用HttpClient对象方式从服务器端获取数据
                 HttpClient httpClient = new DefaultHttpClient();
                 HttpGet httpRequest = new HttpGet(strUrl);
                 try{
                    
                    // 获得HttpResponse对象
                    HttpResponse httpResponse = httpClient.execute(httpRequest);
                    Log.i(TAG, "statue code = " + httpResponse.getStatusLine().getStatusCode());
                    
                    if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

                        // 取得返回的数据
                        strResult = EntityUtils.toString(httpResponse.getEntity());

                        parseJsonMulti(strResult);
                    }
                } catch (ClientProtocolException e) {
                    tvJson.setText("protocol error");
                    e.printStackTrace();
                } catch (IOException e) {
                    tvJson.setText("IO error");
                    e.printStackTrace();
                }

           }

        });
        newThread.start(); 

产生原因:

    是在AndroidManifest.xml文件中没有添加访问网络的权限,即<uses-permission android:name="android.permission.INTERNET" />,添加后即可解决。

注意:android中诸如访问网络的服务,也都需放在线程中

抱歉!评论已关闭.