第十天.Android网络与通信

10.1 Android网络通讯介绍

10.1.1 网络通讯技术

  • Java.net
  • Apache HttpClient
  • Socket技术
  • 装载网页
  • WiFi技术
  • Bluetooth蓝牙

10.2 Java.net

10.2.2主Activity

public class Activity01 extendsActivity{
       publicvoid onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.main)        
              Buttonbutton_http = (Button) findViewById(R.id.Button_HTTP);
              /*监听button的事件信息 */
              button_http.setOnClickListener(newButton.OnClickListener() {
                     publicvoid onClick(View v){
                     /*新建一个Intent对象 */
                     Intentintent = new Intent();
                     /*指定intent要启动的类 */
                     intent.setClass(Activity01.this,Activity02.class);
                     /*启动一个新的Activity*/
                     startActivity(intent);
                     /*关闭当前的Activity*/
                     Activity01.this.finish();
                     }
              });

Activity02是直接获取数据的demo!

Button button_Get = (Button)findViewById(R.id.Button_Get);
              /*监听button的事件信息 */
              button_Get.setOnClickListener(newButton.OnClickListener() {
                     publicvoid onClick(View v)
                     {
                            /*新建一个Intent对象 */
                            Intentintent = new Intent();
                            /*指定intent要启动的类 */
                            intent.setClass(Activity01.this,Activity03.class);
                            /*启动一个新的Activity*/
                            startActivity(intent);
                            /*关闭当前的Activity*/
                            Activity01.this.finish();
                     }
              });

Activity03是以Get方式上传参数的demo!

Button button_Post = (Button)findViewById(R.id.Button_Post);
              /*监听button的事件信息 */
              button_Post.setOnClickListener(newButton.OnClickListener() {
                     publicvoid onClick(View v)
                     {
                            /*新建一个Intent对象 */
                            Intentintent = new Intent();
                            /*指定intent要启动的类 */
                            intent.setClass(Activity01.this,Activity04.class);
                            /*启动一个新的Activity*/
                            startActivity(intent);
                            /*关闭当前的Activity*/
                            Activity01.this.finish();
                     }
              });
       }
} //结束Activity1类

Activity04是以Post方式上传参数的demo!

10.2.3 直接获取数据

//http地址
String httpUrl ="http://serverip:8080/AndroidAppServer/index.jsp";
//获得的数据
String resultData = ""; URLurl = null;
//构造一个URL对象
url = new URL(httpUrl);
       //使用HttpURLConnection打开连接
HttpURLConnection urlConn =(HttpURLConnection) url.openConnection();
//得到读取的内容(流)
InputStreamReader in = newInputStreamReader(urlConn.getInputStream());
// 为输出创建BufferedReader
BufferedReader buffer = newBufferedReader(in);
String inputLine = null;
//使用循环来读取获得的数据
while (((inputLine = buffer.readLine())!= null)){
       resultData+= inputLine + "";
}

研究HttpURLConnectionDemo工程(Activity02.java) serverip要换成真实IP,不能用localhost或127.0.0.1

10.2.4 以Get方式上传参数

String httpUrl = "http://192.168.1.110:8080/httpget.jsp?par=abcdefg";
       URLurl = new URL(httpUrl);
       //使用HttpURLConnection打开连接
       HttpURLConnectionurlConn = (HttpURLConnection) url.openConnection();
       //得到读取的内容(流)
       InputStreamReaderin = new InputStreamReader(urlConn.getInputStream());
       //为输出创建BufferedReader
       BufferedReaderbuffer = new BufferedReader(in);
       StringinputLine = null;
       //使用循环来读取获得的数据
       while(((inputLine = buffer.readLine()) != null)){ resultData += inputLine +""; }  
       //关闭InputStreamReader
       in.close();
       //关闭http连接
       urlConn.disconnect();

研究HttpURLConnectionDemo工程(Activity03.java) serverip要换成真实IP,不能用localhost或127.0.0.1

10.2.5 以Post方式上传参数

String httpUrl ="http://192.168.1.110:8080/httpget.jsp";
URL url = new URL(httpUrl);         
HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
//因为这个是post请求,设立需要设置为true
urlConn.setDoOutput(true);urlConn.setDoInput(true);
urlConn.setRequestMethod("POST");          // 设置以POST方式
urlConn.setUseCaches(false);                   // Post 请求不能使用缓存
urlConn.setInstanceFollowRedirects(true);
urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
urlConn.connect();
DataOutputStream out = newDataOutputStream(urlConn.getOutputStream());
String content = "par=" +URLEncoder.encode("ABCDEFG", "gb2312"); //要上传的参数
out.writeBytes(content);                   //将要上传的内容写入流中
out.flush();        out.close();
//获取数据
BufferedReader reader = newBufferedReader(new InputStreamReader(urlConn.getInputStream()));
String inputLine = null;
while (((inputLine = reader.readLine())!= null)){resultData += inputLine + "";}  
       reader.close();urlConn.disconnect();

研究HttpURLConnectionDemo工程(Activity03.java) Serverip要换成真实IP,不能用localhost或127.0.0.1

main.xml

<LinearLayout 
        xmlns:android="http://schemas.android.com/apk/res/android" 
        android:orientation="vertical" 
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent">
        <TextView 
                android:layout_width="fill_parent" 
                android:layout_height="wrap_content" 
                android:text="通过下面的按钮进行不同方式的连接"/>
        <Button 
                android:id="@+id/Button_HTTP" 
                android:layout_width="fill_parent" 
                android:layout_height="wrap_content" 
                android:text="直接获取数据"/>
        <Button 
                android:id="@+id/Button_Get" 
                android:layout_width="fill_parent" 
                android:layout_height="wrap_content" 
                android:text="以GET方式传递数据"/>
        <Button 
                android:id="@+id/Button_Post" 
                android:layout_width="fill_parent" 
                android:layout_height="wrap_content" 
                android:text="以POST方式传递数据"/>
</LinearLayout>

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.lxt008"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Activity01"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
                <activity android:name="Activity02"></activity>
                <activity android:name="Activity03"></activity>
                <activity android:name="Activity04"></activity>
    </application>
        <uses-permission android:name="android.permission.INTERNET" />
    <uses-sdk android:minSdkVersion=“7" />
</manifest>

10.3 ApacheHttpClient

c10.3.1 使用HttpClient:主Activity

Button button_Get = (Button)findViewById(R.id.Button_Get);
button_Get.setOnClickListener(newButton.OnClickListener() {
       publicvoid onClick(View v){
              Intentintent = new Intent(); /* 新建一个Intent对象 */
              /*指定intent要启动的类 */
              intent.setClass(Activity01.this,Activity02.class);                  
              startActivity(intent);/* 启动一个新的Activity*/                      Activity01.this.finish();/* 关闭当前的Activity*/ }
              });
Button button_Post = (Button)findViewById(R.id.Button_Post);
button_Post.setOnClickListener(newButton.OnClickListener() {
       publicvoid onClick(View v){
              Intentintent = new Intent();
              /*指定intent要启动的类 */
              intent.setClass(Activity01.this,Activity03.class);
              startActivity(intent);                                      Activity01.this.finish();}
              });   
       }

研究ApacheHttpClientDemo工程(Activity01.java) serverip要换成真实IP,不能用localhost或127.0.0.1

10.3.2 HttpClient:HttpGet

String httpUrl ="http://192.168.1.110:8080/httpget.jsp?par=HttpClient_android_Get";
//HttpGet连接对象
HttpGet httpRequest = newHttpGet(httpUrl);
//取得HttpClient对象      
HttpClient httpclient = newDefaultHttpClient();  
//请求HttpClient,取得HttpResponse
HttpResponse httpResponse = httpclient.execute(httpRequest);
//请求成功
if (httpResponse.getStatusLine().getStatusCode()== HttpStatus.SC_OK){
       //取得返回的字符串
       StringstrResult = EntityUtils.toString(httpResponse.getEntity());
       mTextView.setText(strResult);
}
else{
       mTextView.setText("请求错误!");
}

研究ApacheHttpClientDemo工程(Activity02.java) serverip要换成真实IP,不能用localhost或127.0.0.1

10.3.3 HttpClient:HttpPost

String httpUrl = "http://192.168.1.110:8080/httpget.jsp";
//HttpPost连接对象
HttpPost httpRequest = newHttpPost(httpUrl);
//使用NameValuePair来保存要传递的Post参数
List params = newArrayList();
//添加要传递的参数
params.add(newBasicNameValuePair("par", "HttpClient_android_Post"));
//设置字符集
HttpEntity httpentity = newUrlEncodedFormEntity(params, "gb2312");
//请求httpRequest
httpRequest.setEntity(httpentity);
//取得默认的HttpClient
HttpClient httpclient = newDefaultHttpClient();
//取得HttpResponse
HttpResponse httpResponse =httpclient.execute(httpRequest);
if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
       StringstrResult = EntityUtils.toString(httpResponse.getEntity());}

研究ApacheHttpClientDemo工程(Activity03.java) serverip要换成真实IP,不能用localhost或127.0.0.1

10.4 装载并显示Web网页

10.4.1 用线程刷新网页显示

public void onCreate(BundlesavedInstanceState){ new Thread(mRunnable).start(); //开启线程 }
       //刷新网页显示
       privatevoid refresh(){        
              URLurl = new URL("http://192.168.1.110:8080/date.jsp");
              HttpURLConnectionurlConn = (HttpURLConnection) url.openConnection();
              InputStreamReaderin = new InputStreamReader(urlConn.getInputStream());
              BufferedReaderbuffer = new BufferedReader(in);
              StringinputLine = null;
              //使用循环来读取获得的数据 //关闭InputStreamReader// 设置显示取得的内容 }
}
private Runnable mRunnable = newRunnable()  {
       publicvoid run()  {
             while (true) {         Thread.sleep(5 * 1000);
                 //发送消息
                 mHandler.sendMessage(mHandler.obtainMessage());  };
         Handler mHandler = new Handler() {
           public void handleMessage(Message msg)  {
             super.handleMessage(msg);
             refresh();
           } };

研究HttpURLConnectionRefresh工程

10.4.2 装载网页并显示

WebView webView = (WebView)findViewById(R.id.webview);
String html ="Hello lxt008!!!";
//装载页面,你可以换成URL地址。
webView.loadDataWithBaseURL("Demo",html, "text/html", "utf-8", null);
//设置支持JS
webView.getSettings().setJavaScriptEnabled(true);
//设置浏览器客户端
webView.setWebChromeClient(newWebChromeClient());

10.5 Socket编程复习

  • 以前课程中学过Socket编程。
  • 研究SocketDemo以复习巩固Socket在Android中的使用。

示例下载