android get请求数据

  
     //新建Handler的对象,在这里接收Message,然后更新TextView控件的内容
     private Handler handler = new Handler() {

         @Override
         public void handleMessage(Message msg) {
             super.handleMessage(msg);
             switch (msg.what) {
             case SHOW_RESPONSE:
                 String response = (String) msg.obj;
                 Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();
              
                 break;
 
             default:
                 break;
             }            
         }
 
     };

*********************************************************************************

//请求地图平台
        ditupingtai.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                new Thread(new Mytheard()).start();
            }
        });

        
    }
      class  Mytheard extends Thread{
          @Override
        public void run() {
              //用HttpClient发送请求,分为五步
                              //第一步:创建HttpClient对象
                               HttpClient httpCient = new DefaultHttpClient();
                               //第二步:创建代表请求的对象,参数是访问的服务器地址
                               HttpGet httpGet = new HttpGet("http://www.baidu.com");
                               
                               try {
                                  //第三步:执行请求,获取服务器发还的相应对象
                                  HttpResponse httpResponse = httpCient.execute(httpGet);
                                   //第四步:检查相应的状态是否正常:检查状态码的值是200表示正常
                                   if (httpResponse.getStatusLine().getStatusCode() == 200) {
                                       //第五步:从相应对象当中取出数据,放到entity当中
                                       HttpEntity entity = httpResponse.getEntity();
                                       String response = EntityUtils.toString(entity,"utf-8");//将entity当中的数据转换为字符串
                                       
                                       //在子线程中将Message对象发出去
                                       Message message = new Message();
                                       message.what = SHOW_RESPONSE;
                                       message.obj = response.toString();
                                       handler.sendMessage(message);
                                   }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
              
            
        }
      }  


你可能感兴趣的:(android)