您的位置:首页 > 理论基础 > 计算机网络

Android HttpURLConnection 网络通信实时更新

2014-05-13 16:29 501 查看
前言
         欢迎大家我分享和推荐好用的代码段~~
声明
         欢迎转载,但请保留文章原始出处:

         CSDN:
http://www.csdn.net

         雨季o莫忧离:http://blog.csdn.net/luckkof

正文

 

首先,创建一个显示系统当前时间的jsp网页文件,代码如下:

[html] view
plaincopy

<html>  

  <head>  

    <title>My JSP 'index.jsp' starting page</title>  

  </head>   

  <body>  

    <%  

        String type = request.getParameter("par");  

        String result = new String(type.getBytes("iso-8859-1"),"gb2312");  

        out.println("<h1>parameters:"+result+"</h1>");  

     %>  

  </body>  

</html>  

下面通过Http连接来读取网页,每隔5秒钟,程序自己刷新。要实时的从网页获取数据,其实就是吧获取网络数据的代码写到线程中,不停的进行更新。需要说明一点:android中更新视图不能直接在线程中进行,所以这里需要使用handler来实现更新,具体代码如下:

[java] view
plaincopy

package com.android;  

  

import java.io.BufferedReader;  

import java.io.IOException;  

import java.io.InputStreamReader;  

import java.net.HttpURLConnection;  

import java.net.MalformedURLException;  

import java.net.URL;  

  

import android.app.Activity;  

import android.os.Bundle;  

import android.os.Handler;  

import android.os.Message;  

import android.util.Log;  

import android.view.View;  

import android.view.View.OnClickListener;  

import android.widget.Button;  

import android.widget.TextView;  

  

public class MainActivity extends Activity {  

    private final String TAG = "MainActivity"   ;  

    private TextView textView;  

    private Button button;  

    /** Called when the activity is first created. */  

    @Override  

    public void onCreate(Bundle savedInstanceState) {  

        super.onCreate(savedInstanceState);  

        setContentView(R.layout.http);  

          

        textView = (TextView)findViewById(R.id.text);  

        button = (Button)findViewById(R.id.button);  

        button.setOnClickListener(new OnClickListener() {  

            @Override  

            public void onClick(View v) {  

                refresh();  

            }  

        });  

        new Thread(mRunnable).start();  

    }  

      

    //刷新网页显示  

    private void refresh(){  

        String httpUrl = "http://127.0.0.1:8080/test/currentDate.jsp";  

        String result = "";  

        URL url = null;  

        try{  

            //构造一个URL对象  

            url = new URL(httpUrl);  

        }catch (MalformedURLException e) {  

            Log.e(TAG, "MalformedURLException");  

            e.printStackTrace();  

        }  

        if(url != null){  

            try{  

                //使用httpURLConnection打开连接  

                HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();  

                //得到读取的内容  

                InputStreamReader inReader = new InputStreamReader(urlConnection.getInputStream());  

                //为输出创建BufferedReader  

                BufferedReader bufferedReader = new BufferedReader(inReader);  

                String line = null;  

                //使用循环来读取获得的数据  

                while((line=bufferedReader.readLine())!=null){  

                    result += line +"\n";  

                }  

                //关闭InputStreamReader  

                inReader.close();  

                //关闭Http连接  

                urlConnection.disconnect();  

                if(result.equals("")){  

                    textView.setText("读取的内容为null");  

                }else{  

                    textView.setText(result);  

                }  

            }catch (IOException e) {  

                // TODO: handle exception  

                Log.e(TAG, "IOException");  

                e.printStackTrace();  

            }  

        }else{  

            Log.e(TAG, "url null");  

        }  

    }  

      

    private Runnable mRunnable = new Runnable() {  

        @Override  

        public void run() {  

            while(true){  

                try{  

                    Thread.sleep(5 * 1000);  

                    //发送消息  

                    handler.sendMessage(handler.obtainMessage());  

                }catch (InterruptedException e) {  

                    // TODO: handle exception  

                    Log.e(TAG, "InterruptedException");  

                    e.printStackTrace();  

                }  

            }  

        }  

    };  

      

    Handler handler = new Handler(){  

        public void handleMessage(Message msg){  

            super.handleMessage(msg);  

            refresh();  

        }  

    };  

}  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息