1. 程式人生 > >android ——網絡編程

android ——網絡編程

ins blog tco vertica ani n) exe lns amr

一、WebView

這個View就是一個瀏覽器,用於展示網頁的。

布局文件:

 1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2     android:layout_width="match_parent"
 3     android:layout_height="match_parent"
 4     android:orientation="vertical">
 5 
 6     <WebView
 7         android:id="@+id/web_view"
8 android:layout_width="match_parent" 9 android:layout_height="match_parent"> 10 </WebView> 11 12 </LinearLayout>

java代碼:

 1 public class MainActivity extends AppCompatActivity{
 2     @Override
 3     protected void onCreate(Bundle savedInstanceState) {
 4         super
.onCreate(savedInstanceState); 5 setContentView(R.layout.activity_main); 6 7 WebView webView = (WebView) findViewById(R.id.web_view); 8 webView.getSettings().setJavaScriptEnabled(true); 9 webView.setWebViewClient(new WebViewClient()); 10 webView.loadUrl("http://www.baidu.com");
11 } 12 }

webView.getSettings().setJavaScriptEnabled(true)這個方法傳入true,讓WebView支持JavaScript腳本

webView.setWebViewClient(new WebViewClient()),實現了當需要從一個網頁跳到另一個網頁的時候,希望也在這個WebView中顯示

AndroidManifest文件權限添加:

<uses-permission android:name="android.permission.INTERNET"/>

效果:

技術分享

二、HTTP協議訪問數據

  工作原理:客戶端向服務器發出一條HTTP請求,服務器收到請求後會返回一些數據給客戶端,然後客戶端再對數據進行解析和處理。

  1、使用HttpURLConnection

    基本用法:

      * 首先獲取到HttpURLConnection的實例

  URL url = new URL("https://www.baidu.com");
  HttpURLConnection connection = (HttpURLConnection) url.openConnection();

      *設置HTTP請求是希望從服務器獲取數據(GET),還是希望提交數服務器(POST) 

  connection.setRequestMethod("GET");

      *設置連接超時的時間,讀取超時的時間:

  connection.setConnectTimeout(8000);
  connection.setReadTimeout(8000);

      *調用getInputStream()方法獲取到服務器的輸入流:

  InputStream in = connection.getInputStream();

      *最後調用disconnect()把這個HTTP連接關掉:

  connection.disconnect();

實例應用程序:

  布局代碼:

 1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2     android:layout_width="match_parent"
 3     android:layout_height="match_parent"
 4     android:orientation="vertical">
 5 
 6     <Button
 7         android:id="@+id/send_request"
 8         android:layout_width="match_parent"
 9         android:layout_height="wrap_content"
10         android:text="發送" />
11 
12     <ScrollView
13         android:layout_width="match_parent"
14         android:layout_height="match_parent">
15 
16         <TextView
17             android:id="@+id/response_text"
18             android:layout_width="match_parent"
19             android:layout_height="wrap_content" />
20     </ScrollView>
21 
22 </LinearLayout>

  java代碼:

 1 public class MainActivity extends AppCompatActivity{
 2 
 3     TextView responseText;//用於展示從服務器獲取到的文本的控件
 4     @Override
 5     protected void onCreate(Bundle savedInstanceState) {
 6         super.onCreate(savedInstanceState);
 7         setContentView(R.layout.activity_main);
 8 
 9         //控件註冊
10         final Button sendRequest = (Button) findViewById(R.id.send_request);
11         responseText = (TextView) findViewById(R.id.response_text);
12 
13         //按鈕相應
14         sendRequest.setOnClickListener(new View.OnClickListener() {
15             @Override
16             public void onClick(View view) {
17                 sendRequestWithHttpURLConnection();
18             }
19         });
20     }
21 
22     private void sendRequestWithHttpURLConnection(){
23 
24         //開啟線程來發起網絡請求
25         new Thread(new Runnable() {
26             @Override
27             public void run() {
28                 HttpURLConnection connection = null;
29                 BufferedReader reader = null;
30                 try{
31                     URL url = new URL("https://www.baidu.com");
32                     connection = (HttpURLConnection) url.openConnection();
33                     connection.setRequestMethod("GET");
34                     connection.setConnectTimeout(8000);
35                     connection.setReadTimeout(8000);
36                     InputStream in = connection.getInputStream();
37 
38                     //對獲取到的輸入流進行讀取
39                     reader = new BufferedReader(new InputStreamReader(in));
40                     StringBuilder response = new StringBuilder();
41                     String line;
42                     while ((line = reader.readLine()) != null){
43                         response.append(line);
44                     }
45                     showResponse(response.toString());
46                 }catch (Exception e){
47                     e.printStackTrace();
48                 }finally {
49                     if(reader !=  null){
50                         try{
51                             reader.close();
52                         }catch (IOException e){
53                             e.printStackTrace();
54                         }
55                     }
56                     if(connection != null){
57                         connection.disconnect();
58                     }
59                 }
60             }
61         }).start();
62     }
63 
64     private void showResponse(final String response){
65         runOnUiThread(new Runnable() {
66             @Override
67             public void run() {
68                 //UI操作
69                 responseText.setText(response);
70             }
71         });
72     }
73 }

效果:

技術分享

  2、使用OkHttp

    這是一個用來代替HttpURLConnection的開源庫

    基本用法:

      *添加OkHttp庫的依賴

compile ‘com.squareup.okhttp3:okhttp:3.9.0‘

      *創建一個OkHttpClient的實例

OkHttpClient client = new OkHttpClient();

      *創建一個Request實例,並連綴其他方法豐富這個對象

Request request = new Request.Builder()
  .url("http://www.baidu.com")
  .build();

      *獲取返回的數據

  Response response = client.newCall(request).execute();

修改上面的程序:

 1 public class MainActivity extends AppCompatActivity{
 2 
 3     TextView responseText;//用於展示從服務器獲取到的文本的控件
 4     @Override
 5     protected void onCreate(Bundle savedInstanceState) {
 6         super.onCreate(savedInstanceState);
 7         setContentView(R.layout.activity_main);
 8 
 9         //控件註冊
10         final Button sendRequest = (Button) findViewById(R.id.send_request);
11         responseText = (TextView) findViewById(R.id.response_text);
12 
13         //按鈕相應
14         sendRequest.setOnClickListener(new View.OnClickListener() {
15             @Override
16             public void onClick(View view) {
17                 sendRequestWithHttpURLConnection();
18             }
19         });
20     }
21 
22     private void sendRequestWithHttpURLConnection(){
23 
24         //開啟線程來發起網絡請求
25         new Thread(new Runnable() {
26             @Override
27             public void run() {
28                 try{
29                     OkHttpClient client = new OkHttpClient();
30                     Request request = new Request.Builder()
31                             .url("http://www.baidu.com")
32                             .build();
33                     Response response = client.newCall(request).execute();
34                     String responseData = response.body().string();
35                     showResponse(responseData);
36                 }catch (Exception e){
37                     e.printStackTrace();
38                 }
39             }
40         }).start();
41     }
42 
43     private void showResponse(final String response){
44         runOnUiThread(new Runnable() {
45             @Override
46             public void run() {
47                 //UI操作
48                 responseText.setText(response);
49             }
50         });
51     }
52 }

效果同樣。。

android ——網絡編程