08网络技术

本节内容:WebView 的用法、使用HTTP 协议访问网络(两种方法,其一已过时)、解析XML 格式数据(下载安装Apache服务器)、


WebView 的用法---------------------------------------------

    借助它我们就可以在自己的应用程序里嵌入一个浏览器,从而非常轻松地展示各种各样的网页。

    新建项目,主活动布局文件中添加一个WebView控件:

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

    修改主活动:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public  class  MainActivity  extends  Activity {
 
     private  WebView webView;
 
     @Override
     protected  void  onCreate(Bundle savedInstanceState) {
         super .onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
 
         webView = (WebView) findViewById(R.id.web_view);
         webView.getSettings().setJavaScriptEnabled( true );
         webView.setWebViewClient( new  WebViewClient() {
             @Override
             public  boolean  shouldOverrideUrlLoading(WebView view, String url) {
                 view.loadUrl(url);  // 根据传入的参数再去加载新的网页
                 return  true // 表示当前WebView可以处理打开新网页的请求,不用借助系统浏览器
             }
         });
         webView.loadUrl( "http://www.baidu.com" );
     }
}

    首先使用findViewById()方法获取到了WebView 的实例,然后调用WebView 的getSettings()方法可以去设置一些浏览器的属性,这里我们并不去设置过多的属性,只是调用了setJavaScriptEnabled()方法来让WebView 支持JavaScript 脚本。

    接下来是非常重要的一个部分,我们调用了WebView 的setWebViewClient()方法,并传入了WebViewClient 的匿名类作为参数,然后重写了shouldOverrideUrlLoading()方法。这就表明当需要从一个网页跳转到另一个网页时,我们希望目标网页仍然在当前WebView 中显示,而不是打开系统浏览器。

    最后一步就非常简单了,调用WebView 的loadUrl()方法,并将网址传入,即可展示相应网页的内容。

    

    访问网络是需要声明权限的,因此我们还得修改AndroidManifest.xml 文件,并加入权限声明,如下所示:

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


    更多高级用法略。


使用HTTP 协议访问网络-----------------------------------------------------


    HTTP工作原理:客户端向服务器发出一条HTTP 请求,服务器收到请求之后会返回一些数据给客户端,然后客户端再对这些数据进行解析和处理就可以了。


    简单来说,WebView 已经在后台帮我们处理好了发送HTTP 请求、接收服务响应、解析返回数据,以及最终的页面展示这几步工作。

    在Android 上发送HTTP 请求的方式一般有两种,HttpURLConnection 和HttpClient。

    

使用HttpURLConnection:


    1、首先需要获取到HttpURLConnection 的实例,一般只需new 出一个URL 对象,并传入目标的网络地址,然后调用一下openConnection()方法即可,如下所示:

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

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

    2、设置一下HTTP 请求所使用的方法。常用的方法主要有两个,GET 和POST。GET 表示希望从服务器那里获取数据,而POST 则表示希望提交数据给服务器。写法如下:

    connection.setRequestMethod("GET");

    3、进行一些自由的定制了,比如设置连接超时、读取超时的毫秒数,以及服务器希望得到的一些消息头等。这部分内容根据自己的实际情况进行编写,示例写法如下:

    connection.setConnectTimeout(8000);

    connection.setReadTimeout(8000);

    4、之后再调用getInputStream()方法就可以获取到服务器返回的输入流了,剩下的任务就是对输入流进行读取,如下所示:

    InputStream in = connection.getInputStream();

    5、最后可以调用disconnect()方法将这个HTTP 连接关闭掉,如下所示:

    connection.disconnect();


栗子:

    新建项目,主活动布局如下:

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

     主活动:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
public  class  MainActivity  extends  Activity  implements  View.OnClickListener {
 
     public  static  final  int  SHOW_RESPONSE= 0 ; //用于更新操作
     private  Button sendRequest;
     private  TextView responseText;
 
 
     //用于处理和发送消息的Handler
     private  Handler handler= new  Handler(){
         public  void  handleMessage(Message msg){
              switch  (msg.what){
                 case  SHOW_RESPONSE:
                     try {   String response=(String)msg.obj;
                     //进行UI操作,将结果显示到界面上
                     responseText.setText(response);
 
                } catch (Exception e){
                     e.printStackTrace();
                 }
              }
         }
     };
 
 
 
     @Override
     protected  void  onCreate(Bundle savedInstanceState) {
         super .onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
         sendRequest=(Button)findViewById(R.id.send_request);
         responseText=(TextView)findViewById(R.id.response_text);
         sendRequest.setOnClickListener( this );
     }
 
     @Override
     public  void  onClick(View v) {
         if (v.getId()==R.id.send_request){
             sendRequestWithHttpURLConnection();
         }
     }
 
     private  void  sendRequestWithHttpURLConnection(){
         //开启线程来发起网络请求
         new  Thread( new  Runnable() {
             @Override
             public  void  run() {
                 HttpURLConnection connection= null ;
                 try {
                     URL url= new  URL( "https://www.baidu.com" );
                     connection=(HttpURLConnection)url.openConnection();
                     connection.setRequestMethod( "GET" );
                     connection.setConnectTimeout( 8000 );
                     connection.setReadTimeout( 8000 );
                     //int n = connection.getResponseCode();
                     InputStream in=connection.getInputStream();
                     //下面对获取到的输入流进行读取
                     BufferedReader bufr= new  BufferedReader( new  InputStreamReader(in));
                     StringBuilder response= new  StringBuilder();
                     String line= null ;
                     while ((line=bufr.readLine())!= null ){
                         response.append(line);
                     }
 
                     Message message= new  Message();
                     message.what=SHOW_RESPONSE;
                     //将服务器返回的数据存放到Message中
                     message.obj=response.toString();
                     handler.sendMessage(message);
                 } catch (Exception e){
                     e.printStackTrace();
                 } finally  {
                     if (connection!= null ){
                         connection.disconnect();
                     }
                 }
             }
         }).start();
     }
}

    最后声明权限:

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


    如果是想要提交数据给服务器只需要将HTTP 请求的方法改成POST,并在获取输入流之前把要提交的数据写出即可。注意每条数据都要以键值对的形式存在,数据与数据之间用&符号隔开,比如说我们想要向服务器提交用户名和密码,就可以这样写:

    connection.setRequestMethod("POST");

    DataOutputStream out = new DataOutputStream(connection.getOutputStream());

    out.writeBytes("username=admin&password=123456");


使用HttpClient:(API22之后不推荐使用)

    栗子:(布局和上例相同)

1
2
3
4
5
6
7
8
9
HttpClient httpClient =  new  DefaultHttpClient();
HttpGet httpGet =  new  HttpGet( "http://www.baidu.com" );
HttpResponse httpResponse = httpClient.execute(httpGet);
if  (httpResponse.getStatusLine().getStatusCode() ==  200 ) {
     // 请求和响应都成功了
     HttpEntity entity = httpResponse.getEntity();
     String response = EntityUtils.toString(entity, "utf-8" );
     ......
}


解析XML 格式数据---------------------------------------------------


下载安装Apache服务器:

    下载地址是:http://httpd.apache.org/download.cgi

    1、下载解压,修改conf文件(根目录&端口);

    2、在命令行(以管理员身份运行)cd到解压后目录中的bin文件夹,执行安装命令:httpd -k install(卸载:httpd -k uninstall)

    3、几种启动方法:ApacheMonitor.exe;httpd -k start;计算机服务中启动;

    4、测试:localhost:8088或者127.0.0.1:8088


Pull 解析方式:

SAX 解析方式:


解析JSON 格式数据-----------------------------------------------


比起XML,JSON 的主要优势在于它的体积更小,在网络上传输的时候可以更省流量。但缺点在于,它的语义性较差,看起来不如XML 直观。


使用JSONObject:

使用GSON:

下载地址是:http://code.google.com/p/google-gson/downloads/list



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值