<Android基础> (九)网络技术

第九章 网络技术

9.1 WebView的用法

新建项目WebViewTest,修改activity_main中的代码

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <WebView
        android:id="@+id/web_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
      />

</LinearLayout>

修改MainActivity中的代码

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        WebView webView = (WebView)findViewById(R.id.web_view);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient());
        webView.loadUrl("http://www.baidu.com");
    }
}

WebView的getSettings()设置属性,调用了setJavaScriptEnabled()方法让WebView来支持JavaScript脚本。

调用setWebViewClient()方法并传入一个WebViewClient实例,保证当一个网页跳转到另一个网页时令目标网页仍然在当前WebView中显示,而不是打开系统浏览器。

最后调用loadUrl()方法,传入网址。

需要加入权限声明

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

运行程序:

9.2 使用HTTP协议访问网络

9.2.1 使用HttpURLConnection

新建项目NetworkTest项目

修改activiy_main中的代码

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <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_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </ScrollView>

</LinearLayout>

修改MainActivity中的代码

在Send Request按钮的点击事件中调用了sendRequestWithHttpURLConnection()方法,方法中先启动一个子线程,然后在子线程里使用HttpURLConnection发出一条HTTP请求,目的地址为百度首页。接着利用BufferedReader对服务器返回的流进行读取,并将结果传入到showResponse()方法中。在showResponse()方法中调用一个runOnUiThread()方法,在该方法的匿名类参数中进行操作,将返回的数据显示到界面上。

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private 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();
        }
    }

    public void sendRequestWithHttpURLConnection(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try{
                    URL url = new URL("https://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 (Exception e){
                            e.printStackTrace();
                        }
                    }
                    if(connection != null){
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

    private void showResponse(final String response){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                responseText.setText(response);
            }
        });
    }
}

最后声明一下网络权限

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

运行程序:

提交数据给服务器,只需要将Http请求的方法改成POST,并在获取输入流之前把要提交的数据写出即可。每条数据需要以键值对的形式存在,数据与数据之间用&符号分开。

比如说想要向服务器提供用户名和密码,就可以这样写:

connection.setRequestMethod("POST");
DataOutputStram out = New DataOutputStream(conection.getOutputStream());
out.writeBytes("username=admin&password=123456");

9.2.2 使用OkHttp

OkHttp比起原生的HttpURLConnection,是广大Android开发者的首选。

首先在app/build.gradle的闭包dependencies中添加内容

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

OkHttp的具体用法,首先创建OkHttpClient的实例,接下来如果要发送一个HTTP请求,就需要创建一个Request对象。通过连缀的方法来丰富Request对象。

之后调用OkHttpClient的newCall()方法来创建一个Call对象,并且调用它的execute()方法来发送请求并获取服务器返回的数据。

 POST和GET略有不同。

在原MainActivity中修改

  @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:www.baidu.com")
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    showResponse(responseData);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

运行程序:

9.3 解析XML数据格式和JSON数据格式

在网络上传输数据最常用的两种格式:XML和JSON

 

posted @ 2019-05-07 16:25  HarSong13  阅读(209)  评论(0编辑  收藏  举报