Android学习笔记(九)——网络技术

一、WebView控件的使用

使用WebView控件可以让我们在应用程序中嵌入一个浏览器,以便更好的展示各种网页内容。
下面是一个测试的小案例:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="cn.edu.hznu.webviewtest.MainActivity">
<WebView
    android:id="@+id/web_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</WebView>
</LinearLayout>

MainActivity.java

package cn.edu.hznu.webviewtest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //得到WebView的实例
        WebView webView=(WebView)findViewById(R.id.web_view);
        //调用getSettings()方法,设置浏览器的属性——支持javaScript脚本
        webView.getSettings().setJavaScriptEnabled(true);
        //调用setWebViewClient方法,传入WebViewClient的实例
        webView.setWebViewClient(new WebViewClient());
        //调用loadUrl方法,传入网址
        webView.loadUrl("http://www.baidu.com");
    }
}

此外,我们需要注意:由于程序中使用到了网络的功能,我们需要在AndroidManifest.xml中声明权限:

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

二、使用HTTP协议访问网络

2.1、使用HttpURLConnection
具体的使用方法如下:
1、 得到HttpURLConnection的实例。

URL url=new URL(“http://www.baidu.com”);
HttpURLConnection conn=(HttpURLConnection)url.openConnection();

2、 设置HTTP请求所使用的方法(GET和POST)

conn.setRequestMethod(“GET”);

3、 根据需要设置一些属性,如连接超时、读取超时等。

conn.setConntectionTimeout(8000);
conn.setReadTimeout(8000);

4、 获取服务器返回的输入流,然后对输入流进行读取数据。

InputStream in=conn.getInputStream();

5、 最后将HTTP连接关闭。

conn.disconnection();

测试的小案例:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="cn.edu.hznu.ex6.MainActivity">
<Button
    android:id="@+id/send_request"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="点击按钮"/>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:id="@+id/response_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </ScrollView>
</LinearLayout>

MainActivity.java

package cn.edu.hznu.ex6;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    TextView responseText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button 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;
                BufferedReader reader = null;
                try {
                    URL url = new URL("http://www.baidu.com");
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    InputStream in = connection.getInputStream();
                    // 下面对获取到的输入流进行读取
                    reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    showResponse(response.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }
    private void showResponse(final String response) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // 在这里进行UI操作,将结果显示到界面上
                responseText.setText(response);
            }
        });
    }
}

注意:不要忘记在AndroidManifest.xml中声明网络权限:

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

下面我们运行项目,点击 “点击按钮”后:
在这里插入图片描述

三、使用OkHttp

在使用之前,由于okhttp不是原生库,需要添加依赖,在app/build.gradle文件中的 dependencies 闭包中添加依赖:

  compile 'com.squareup.okhttp3:okhttp:3.4.1'

具体的使用如下:
1、创建OKHttpClient的实例。

OKHttpClient client=new OKHttpClient();

2、创建Request对象,用以发起HTTP请求。

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

3、发送请求,获取服务器返回的数据。

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

4、获取返回数据的具体内容。

String responseData=response.body().string();

测试的小案例:

activaty_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="cn.edu.hznu.ex6.MainActivity">
<Button
    android:id="@+id/send_request"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="点击按钮"/>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:id="@+id/response_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </ScrollView>
</LinearLayout>

MainActivity.java

package cn.edu.hznu.ex6;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    TextView responseText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button 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) {
          sendRequestWithOkHttp();
        }
    }
    private void sendRequestWithOkHttp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            // 指定访问的服务器地址是电脑本机
                            .url("http://10.0.2.2/get_data.json")
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    showResponse(responseData);

                

} catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
        private void showResponse(final String response) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // 在这里进行UI操作,将结果显示到界面上
                responseText.setText(response);
            }
        });
    }

在上面的布局文件中,主要用到的控件:

  • ScrollView用于滚动查看内容。
  • TextView用来显示服务器返回的数据。
  • Button用来发送HTTP请求。
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小小Java开发者

“是一种鼓励,你懂的”

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值