关于android中的httpclient中httpclient.execute停滞现象解决

最近在做一个android上的项目时,这个项目上有一项程序检测升级的功能,其中使用了apache的httpclient,在使用httpclient时,httpclient.execute(httpget)这个方法返回一个response对象,但是由于一些原因比如找不见httpget中url。或者url错误,导致httpclient.execute这个方法就会一直等待不会继续执行下面的程序,为了避免程序不卡在httpclient.execute这,我们把httpclient.execute放在一个线程中,让程序继续往下走,可以通过httpclient.execute返回对象是否为空来判断是否连接服务器的地址。

实例代码:

…………

           Thread hth = new Thread()

           {

 

              @Override

              public void run() {

                 

                 

                     try {

                    

                         response = client.execute(get);

                     } catch (IllegalArgumentException ec) {

                         response = null;

                         interrupted();

                     } catch (ClientProtocolException e) {

                        

                         response = null;

                         interrupted();

                     } catch (IOException e) {

                        

                         response = null;

                         interrupted();

                     }

                  }

             

             

           };

           hth.start();

 

           try {

          

              Thread.sleep(5000);

              if(response==null)

              {

                 

                  hth.interrupt();

             

                  return false;

              }

           } catch (InterruptedException e) {

             

              e.printStackTrace();

           }

          

          

          

          

          

           if(response.getStatusLine().getStatusCode()==200)

           {

              return getDom(response.getEntity().getContent());

           }

……………………

留下评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注

57 − 54 =