14天學會安卓開發(第十天)Android網路與通訊

查志強發表於2014-06-25

【原文:http://blog.csdn.net/corder_raine/article/details/8317306

14天學會安卓開發  
作者:神祕的N (英文名  corder_raine)
聯絡方式:369428455(反饋)
交流群:284552167(示例,原文件下載)
版權為作者所有,如有轉載請註明出處
目錄             


第十天.Android網路與通訊... 100
10.1  Android網路通訊介紹... 100
10.1.1 網路通訊技術... 100
10.2  Java.net 101
10.2.2主Activity. 101
10.2.3 直接獲取資料... 102
10.2.4 以Get方式上傳引數... 103
10.2.5 以Post方式上傳引數... 103
10.3  ApacheHttpClient 105
10.3.1 使用HttpClient:主Activity. 105
10.3.2 HttpClient:HttpGet 106
10.3.3 HttpClient:HttpPost 107
10.4  裝載並顯示Web網頁... 108
10.4.1 用執行緒重新整理網頁顯示... 108
10.4.2 裝載網頁並顯示... 109
10.5  Socket程式設計複習... 110


第十天.Android網路與通訊
10.1 Android網路通訊介紹
    10.1.1 網路通訊技術
Ø  Java.net
Ø  Apache HttpClient
Ø  Socket技術
Ø  裝載網頁
Ø  WiFi技術
Ø  Bluetooth藍芽
10.2 Java.net
10.2.2Activity
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
publicclass 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!
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
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!
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
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 直接獲取資料
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
//http地址
//獲得的資料
String resultData = ""; URLurl = null;
//構造一個URL物件
url = newURL(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,不能用localhost127.0.0.1  

10.2.4 Get方式上傳引數
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
       URLurl = newURL(httpUrl);
       //使用HttpURLConnection開啟連線
       HttpURLConnectionurlConn = (HttpURLConnection) url.openConnection();
       //得到讀取的內容(流)
       InputStreamReaderin = newInputStreamReader(urlConn.getInputStream());
       //為輸出建立BufferedReader
       BufferedReaderbuffer = newBufferedReader(in);
       StringinputLine = null;
       //使用迴圈來讀取獲得的資料
       while(((inputLine = buffer.readLine()) != null)){ resultData += inputLine +""; } 
       //關閉InputStreamReader
       in.close();
       //關閉http連線
       urlConn.disconnect();
**   研究HttpURLConnectionDemo工程(Activity03.java)
**  serverip要換成真實IP,不能用localhost127.0.0.1

10.2.5 Post方式上傳引數
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
URL url = newURL(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(newInputStreamReader(urlConn.getInputStream()));
String inputLine = null;
while(((inputLine = reader.readLine())!= null)){resultData += inputLine + "";} 
       reader.close();urlConn.disconnect();
**   研究HttpURLConnectionDemo工程(Activity03.java)
**  serverip要換成真實IP,不能用localhost127.0.0.1               

main.xml
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<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
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
      package="com.lxt008"
      android:versionCode="1"
      android:versionName="1.0">
    <applicationandroid:icon="@drawable/icon"android:label="@string/app_name">
        <activityandroid:name=".Activity01"
                  android:label="@string/app_name">
            <intent-filter>
                <actionandroid:name="android.intent.action.MAIN"/>
                <categoryandroid:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
                <activityandroid:name="Activity02"></activity>
                <activityandroid:name="Activity03"></activity>
                <activityandroid:name="Activity04"></activity>
    </application>
        <uses-permissionandroid:name="android.permission.INTERNET"/>
    <uses-sdkandroid:minSdkVersion=“7" />
</manifest>

10.3 ApacheHttpClient   
   10.3.1 使用HttpClient:Activity
1
2
3
4
5
6
7
8
Button button_Get = (Button)findViewById(R.id.Button_Get);
button_Get.setOnClickListener(newButton.OnClickListener() {
       publicvoid onClick(View v){
              Intentintent = newIntent(); /* 新建一個Intent物件 */
              /*指定intent要啟動的類 */
              intent.setClass(Activity01.this,Activity02.class);                 
              startActivity(intent);/* 啟動一個新的Activity*/                      Activity01.this.finish();/* 關閉當前的Activity*/}
              });

1
2
3
4
5
6
7
8
9
Button button_Post = (Button)findViewById(R.id.Button_Post);
button_Post.setOnClickListener(newButton.OnClickListener() {
       publicvoid onClick(View v){
              Intentintent = newIntent();
              /*指定intent要啟動的類 */
              intent.setClass(Activity01.this,Activity03.class);
              startActivity(intent);                                      Activity01.this.finish();}
              });  
       }
**   研究ApacheHttpClientDemo工程(Activity01.java)
**  serverip要換成真實IP,不能用localhost127.0.0.1

10.3.2 HttpClient:HttpGet

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
//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("請求錯誤!");
[align=left]}
**   研究ApacheHttpClientDemo工程(Activity02.java)
**  serverip要換成真實IP,不能用localhost127.0.0.1

10.3.3 HttpClient:HttpPost
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
//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,不能用localhost127.0.0.1

10.4 裝載並顯示Web網頁
  10.4.1 用執行緒重新整理網頁顯示
01
02
03
04
05
06
07
08
09
10
publicvoid onCreate(BundlesavedInstanceState){ newThread(mRunnable).start(); //開啟執行緒 }
       //重新整理網頁顯示
       privatevoid refresh(){       
              URLurl = newURL("http://192.168.1.110:8080/date.jsp");
              HttpURLConnectionurlConn = (HttpURLConnection) url.openConnection();
              InputStreamReaderin = newInputStreamReader(urlConn.getInputStream());
              BufferedReaderbuffer = newBufferedReader(in);
              StringinputLine = null;
              //使用迴圈來讀取獲得的資料 //關閉InputStreamReader// 設定顯示取得的內容 }
}
01
02
03
04
05
06
07
08
09
10
privateRunnable mRunnable = newRunnable()  {
       publicvoid run()  {
             while(true) {         Thread.sleep(5* 1000);
                 //傳送訊息
                 mHandler.sendMessage(mHandler.obtainMessage());  };
         Handler mHandler = newHandler() {
           publicvoid handleMessage(Message msg)  {
             super.handleMessage(msg);
             refresh();
           } };
**   研究HttpURLConnectionRefresh工程

10.4.2 裝載網頁並顯示
1
2
3
4
5
6
7
8
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中的使用。

示例下載

相關文章