Android网络技术(一)——WebView和HTTP协议

一、WebView的用法

新建一个空项目day16_WebViewTest

WebView 应用内嵌浏览器

布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

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

</LinearLayout>

主活动:

public class MainActivity extends AppCompatActivity {

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        WebView webView = findViewById(R.id.web);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient());
        webView.loadUrl("https://bilibili.com");
    }
}

setJavaScriptEnabled()使其支持JS脚本
setWebViewClient()网页跳转时在本控件内进行,而不是打开系统浏览器
loadUrl()传入对应网址

网络权限声明:

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

运行:
在这里插入图片描述

二、使用HTTP协议访问网络

新建一个day16_NetworkTest空项目

1、HttpURLConnection

Android团队推荐使用HttpURLConnection发送HTTP请求,其步骤如下:

  1. 获取HttpURLConnection实例:new一个URL对象,调用openConnection()即可
  2. 用实例设置请求所使用的方法,GETPOST,调用setRequestMethod()
  3. 自由定制,设置连接超时setConnectTimeout()、读取的毫秒数setReadTimeout()、消息头等等
  4. 获取输入流,getInputStream()
  5. 最后关闭连接,disconnect()

举个例子:
布局:

<?xml version="1.0" encoding="utf-8"?>
<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:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/send_request"
        android:text="发送请求"/>
    
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/response_text"/>
    </ScrollView>

</LinearLayout>

活动:

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    TextView textView ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button sendRequest = findViewById(R.id.send_request);
        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("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 (IOException 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() {
                textView.setText(response);
            }
        });
    }
}

我们在子线程内用HttpURLConnection发出了一条HTTP请求,用BufferedReader完成数据流的读取
runOnUiThread()将线程切换到主线程,再更新UI元素【Android不允许子线程UI操作】

最后更新权限:

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

运行:
在这里插入图片描述

2、OkHttp

官网:https://square.github.io/okhttp/

添加依赖:

implementation("com.squareup.okhttp3:okhttp:4.3.1")

Request用法:

  1. 创建OkHttpClient实例:new OkHttpClient()
  2. 创建Request对象:new Request.Builder().url("").build()
  3. 调用实例的newCall() 创建Call对象,调用execute()发送请求获取数据:Response response = client.newCall(request).execute()
  4. 获取返回的内容:response.body().String()

Post用法:

RequestBody requestBody = new FormBody.Builder()
	.add("username", "admin")
	.add("password", "123456")
	.build();

Request request = new Request.Builder()
	.url("")
	.post(requestBody)
	.build()

接下来和Request用法一样

主活动:

private void sendRequestWithOkHttp() {
    new Thread(new Runnable() {
        @Override
        public void run() {
            try{
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url("https://baidu.com")
                        .build();
                Response response = client.newCall(request).execute();
                String responseData = response.body().string();
                showResponse(responseData);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }).start();
}

运行:
在这里插入图片描述

发布了166 篇原创文章 · 获赞 14 · 访问量 9104

猜你喜欢

转载自blog.csdn.net/qq_41205771/article/details/104339432
今日推荐