Android网络编程之Http请求服务器数据(GET方式)

来源:互联网 发布:psp软件 编辑:程序博客网 时间:2024/06/03 18:58

 进行Android应用开发,其中不得不使用到网络编程,最基本的就是向服务器发送Http请求,并接收从服务器返回的数据,该类数据一般为JSON或XML格式。

        向服务器进行请求数据一般有GET、POST两种方式,两者基本类似,以GET居多。本文先讨论使用GET方式向聚合数据API发送请求,以获得手机号码归属地的信息。归属地查询的接口的请求示例为:http://apis.juhe.cn/mobile/get?phone=13429667914&key=您申请的KEY。默认返回的格式为JSON。最后把返回结果显示在TextView上。直接上代码:

[java] view plain copy
 print?
  1. public class MainActivity extends Activity {  
  2.   
  3.     private TextView text;  
  4.     private String url = "http://apis.juhe.cn/mobile/get?phone=13429667914&key=9719c91bd4ac2647c67c6cd067b5cb8e";//向服务器请求的url.  
  5.     private Handler handler = new Handler();//使用Handler更新UI,因为网络操作是在子线程中进行的,子线程不能更新UI,所以只能使用Handler机制;  
  6.   
  7.     @Override  
  8.     protected void onCreate(Bundle savedInstanceState) {  
  9.         super.onCreate(savedInstanceState);  
  10.         setContentView(R.layout.activity_main);  
  11.         text = (TextView) findViewById(id_text);  
  12.   
  13.         //新建线程Thread,开始网络操作。  
  14.         new Thread() {  
  15.             @Override  
  16.             public void run() {  
  17.                 try {  
  18.                     URL httpUrl = new URL(url);  
  19.                     HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();//与服务器建立连接;  
  20.                     conn.setReadTimeout(5000);  
  21.                     conn.setRequestMethod("GET");//设置请求方式为GET  
  22.   
  23.                     final StringBuffer sb = new StringBuffer();//把获取的数据不断存放到StringBuffer中;  
  24.                     BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));//使用reader向输入流中读取数据,并不断存放到StringBuffer中;  
  25.                     String line;  
  26.                     while ((line = reader.readLine()) != null) {//只要还没有读取完,就不断读取;  
  27.                         sb.append(line);//在StringBuffer中添加;  
  28.                     }  
  29.                     handler.post(new Runnable() {//使用Handler更新UI;当然这里也可以使用sendMessage();handMessage()来进行操作;  
  30.                         @Override  
  31.                         public void run() {  
  32.                             text.setText(sb.toString());//StringBuffer转化为String输出;  
  33.                         }  
  34.                     });  
  35.                 } catch (MalformedURLException e) {  
  36.                     e.printStackTrace();  
  37.                 } catch (IOException e) {  
  38.                     e.printStackTrace();  
  39.                 }  
  40.             }  
  41.         }.start();  
  42.     }  
  43. }  
最后返回的结果如截图所示:

。成功接收到从服务器返回的JSON数据。


      如果需要返回的数据为XML,只要重新拼装URL即可。如:"http://apis.juhe.cn/mobile/get?phone=13429667914&key=9719c91bd4ac2647c67c6cd067b5cb8e&dtype=xml";最后返回的结果为XML,截图如下:

      最后开发者根据需要,可以对XML和JSON进行解析,完成业务需求。


github主页:https://github.com/chenyufeng1991  。欢迎大家访问!

0 0
原创粉丝点击