Android HttpURLConnection 網絡通信實時更新

前言
         歡迎大家我分享和推薦好用的代碼段~~
聲明
         歡迎轉載,但請保留文章原始出處:
         CSDN:
http://www.csdn.net
         雨季o莫憂離:http://blog.csdn.net/luckkof

正文

 

首先,創建一個顯示系統當前時間的jsp網頁文件,代碼如下:

[html] view plaincopy
  1. <html>  
  2.   <head>  
  3.     <title>My JSP 'index.jsp' starting page</title>  
  4.   </head>   
  5.   <body>  
  6.     <%  
  7.         String type = request.getParameter("par");  
  8.         String result = new String(type.getBytes("iso-8859-1"),"gb2312");  
  9.         out.println("<h1>parameters:"+result+"</h1>");  
  10.      %>  
  11.   </body>  
  12. </html>  
下面通過Http連接來讀取網頁,每隔5秒鐘,程序自己刷新。要實時的從網頁獲取數據,其實就是吧獲取網絡數據的代碼寫到線程中,不停的進行更新。需要說明一點:android中更新視圖不能直接在線程中進行,所以這裏需要使用handler來實現更新,具體代碼如下:

[java] view plaincopy
  1. package com.android;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.IOException;  
  5. import java.io.InputStreamReader;  
  6. import java.net.HttpURLConnection;  
  7. import java.net.MalformedURLException;  
  8. import java.net.URL;  
  9.   
  10. import android.app.Activity;  
  11. import android.os.Bundle;  
  12. import android.os.Handler;  
  13. import android.os.Message;  
  14. import android.util.Log;  
  15. import android.view.View;  
  16. import android.view.View.OnClickListener;  
  17. import android.widget.Button;  
  18. import android.widget.TextView;  
  19.   
  20. public class MainActivity extends Activity {  
  21.     private final String TAG = "MainActivity"   ;  
  22.     private TextView textView;  
  23.     private Button button;  
  24.     /** Called when the activity is first created. */  
  25.     @Override  
  26.     public void onCreate(Bundle savedInstanceState) {  
  27.         super.onCreate(savedInstanceState);  
  28.         setContentView(R.layout.http);  
  29.           
  30.         textView = (TextView)findViewById(R.id.text);  
  31.         button = (Button)findViewById(R.id.button);  
  32.         button.setOnClickListener(new OnClickListener() {  
  33.             @Override  
  34.             public void onClick(View v) {  
  35.                 refresh();  
  36.             }  
  37.         });  
  38.         new Thread(mRunnable).start();  
  39.     }  
  40.       
  41.     //刷新網頁顯示  
  42.     private void refresh(){  
  43.         String httpUrl = "http://127.0.0.1:8080/test/currentDate.jsp";  
  44.         String result = "";  
  45.         URL url = null;  
  46.         try{  
  47.             //構造一個URL對象  
  48.             url = new URL(httpUrl);  
  49.         }catch (MalformedURLException e) {  
  50.             Log.e(TAG, "MalformedURLException");  
  51.             e.printStackTrace();  
  52.         }  
  53.         if(url != null){  
  54.             try{  
  55.                 //使用httpURLConnection打開連接  
  56.                 HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();  
  57.                 //得到讀取的內容  
  58.                 InputStreamReader inReader = new InputStreamReader(urlConnection.getInputStream());  
  59.                 //爲輸出創建BufferedReader  
  60.                 BufferedReader bufferedReader = new BufferedReader(inReader);  
  61.                 String line = null;  
  62.                 //使用循環來讀取獲得的數據  
  63.                 while((line=bufferedReader.readLine())!=null){  
  64.                     result += line +"\n";  
  65.                 }  
  66.                 //關閉InputStreamReader  
  67.                 inReader.close();  
  68.                 //關閉Http連接  
  69.                 urlConnection.disconnect();  
  70.                 if(result.equals("")){  
  71.                     textView.setText("讀取的內容爲null");  
  72.                 }else{  
  73.                     textView.setText(result);  
  74.                 }  
  75.             }catch (IOException e) {  
  76.                 // TODO: handle exception  
  77.                 Log.e(TAG, "IOException");  
  78.                 e.printStackTrace();  
  79.             }  
  80.         }else{  
  81.             Log.e(TAG, "url null");  
  82.         }  
  83.     }  
  84.       
  85.     private Runnable mRunnable = new Runnable() {  
  86.         @Override  
  87.         public void run() {  
  88.             while(true){  
  89.                 try{  
  90.                     Thread.sleep(5 * 1000);  
  91.                     //發送消息  
  92.                     handler.sendMessage(handler.obtainMessage());  
  93.                 }catch (InterruptedException e) {  
  94.                     // TODO: handle exception  
  95.                     Log.e(TAG, "InterruptedException");  
  96.                     e.printStackTrace();  
  97.                 }  
  98.             }  
  99.         }  
  100.     };  
  101.       
  102.     Handler handler = new Handler(){  
  103.         public void handleMessage(Message msg){  
  104.             super.handleMessage(msg);  
  105.             refresh();  
  106.         }  
  107.     };  
  108. }  


發佈了128 篇原創文章 · 獲贊 10 · 訪問量 73萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章