【安卓】WebView的用法与HTTP访问网络

news2024/9/20 12:36:56

文章目录

      • WebView的用法
      • 使用http访问网络
        • 使用HttpURLConnection
        • 使用OkHttp

前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。 点击跳转到网站。

WebView的用法

  新建一个WebViewTest项目,然后修改activity_main.xml中的代码。在布局中添加webView控件,用来显示网页。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent" >
 <WebView
 android:id="@+id/webView"
 android:layout_width="match_parent"
 android:layout_height="match_parent" />
</LinearLayout>

  然后修改MainActivity中的代码。

public class MainActivity extends AppCompatActivity {

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

  getSettings()方法可以设置一些浏览器的属性。setJavaScriptEnabled()方法,让WebView支持JavaScript脚本。

  修改AndroidManifest.xml文件,并加入权限声明。

在这里插入图片描述

  代码可能会报 net::ERR_CLEARTEXT_NOT_PERMITTED 错误。

  可以创建文件:res/xml/network_security_config.xml。

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">api.example.com(to be adjusted)</domain>
    </domain-config>
</network-security-config>

  然后对AndroidManifest.xml文件做修改。

 <application
     ...
     android:networkSecurityConfig="@xml/network_security_config"
     ...>

使用http访问网络

使用HttpURLConnection

  首先需要获取HttpURLConnection的实例,一般只需创建一个URL对象,并传入目标的网络地址,然后调用一下openConnection()方法即可。

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

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

  HTTP请求常用的方法主要有两个:GET和POST。GET表示希望从服务器那里获取数据,而POST则表示希望提交数据给服务器。

connection.requestMethod = “GET”

  调用getInputStream()方法就可以获取到服务器返回的输入流。

InputStream in = connection.getInputStream();

  最后可以调用disconnect()方法将这个HTTP连接关闭。

connection.disconnect()

  新建一个NetworkTest项目,首先修改activity_main.xml中的代码。在不居中添加一个按钮用于发送HTTP请求,TextView用于将服务器返回的数据显示出来。借助ScrollView控件,以滚动的形式查看屏幕外的内容。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="match_parent"
 android:layout_height="match_parent" >
 <Button
 android:id="@+id/sendRequestBtn"
 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/responseText"
 android:layout_width="match_parent"
 android:layout_height="wrap_content" />
 </ScrollView>
</LinearLayout>

  接着修改MainActivity中的代码。

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.sendRequestBtn);
        responseText = (TextView) findViewById(R.id.responseText);
        sendRequest.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.sendRequestBtn) {
            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 (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);
            }
        });
    }
}

在这里插入图片描述

使用OkHttp

  OkHttp是一个开源项目,它不仅在接口封装上做得简单易用,就连在底层实现上也是自成一派,比起原生的HttpURLConnection,可以说是有过之而无不及,现在已经成了广大Android开发者首选的网络通信库。

  OkHttp的项目主页地址是:https://github.com/square/okhttp。

在使用OkHttp之前,我们需要先在项目中添加OkHttp库的依赖。编辑app/build.gradle文件。

dependencies {
    implementation(libs.appcompat)
    implementation(libs.material)
    implementation(libs.activity)
    implementation(libs.constraintlayout)
    testImplementation(libs.junit)
    androidTestImplementation(libs.ext.junit)
    androidTestImplementation(libs.espresso.core)
    implementation("com.squareup.okhttp3:okhttp:4.4.1")//okHttp
}

  添加上述依赖会自动下载两个库:一个是OkHttp库,一个是Okio库,后者是前者的通信基础。

  修改MainActivity中的代码。

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.sendRequestBtn);
        responseText = (TextView) findViewById(R.id.responseText);
        sendRequest.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.sendRequestBtn) {
//            sendRequestWithHttpURLConnection();
            sendRequestWithOkHttp();
        }
    }

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

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

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2044625.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

管易云与金蝶K3-WISE对接集成发货单查询打通新增其他出库

管易云与金蝶K3-WISE对接集成发货单查询打通新增其他出库 对接系统&#xff1a;管易云 管易云是金蝶旗下专注提供电商企业管理软件服务的子品牌&#xff0c;先后开发了C-ERP、EC-OMS、EC-WMS、E店管家、BBC、B2B、B2C商城网站建设等产品和服务&#xff0c;涵盖电商业务全流程。…

本地连接服务器上docker中的redis

在上一篇本地连接服务器redis这篇文章中详细介绍了。 这里连接服务器中docker中的redis&#xff0c;同样的操作步骤 1.看一下服务器上redis实例的运行状态&#xff1a; [rootiZuf67k70ucx14s6zcv54dZ var]# ps aux | grep redis-server若显示&#xff1a; 则说明服务器上do…

Denser Retriever: RAG中更强大的AI检索器,让您10 分钟内构建聊天机器人应用

一、Denser Retriever 介绍 Denser Retriever 是一个企业级的RAG检索器&#xff0c;将多种搜索技术整合到一个平台中。在MTEB数据集上的实验表明&#xff0c;Denser Retriever可以显著提升向量搜索&#xff08;VS&#xff09;的基线&#xff08;snowflake-arctic-embed-m模型,…

如何在PyCharm使用conda虚拟环境,如何使用远程Linux系统上的conda虚拟环境。

目录 在PyCharm使用conda虚拟环境&#xff08;windows&#xff09; 使用远程Linux系统上的conda虚拟环境 在PyCharm使用conda虚拟环境&#xff08;windows&#xff09; 首先请创建好虚拟环境 点击输入 conda create -n pyspark python3.8 # conda create -n 名字任取 py…

智谱AI与和鲸科技签署战略合作协议,共拓大模型产业应用与人才培养新未来

8月9日&#xff0c;北京智谱华章科技有限公司&#xff08;智谱 AI&#xff09;与上海和今信息科技有限公司&#xff08;和鲸科技&#xff09;在北京签署战略合作协议。智谱 AI 总裁王绍兰与和鲸科技创始人、CEO 范向伟亲临现场&#xff0c;发表致辞并见证签约。智谱 AI AIGC 事…

Python软件包和PIP镜像下载地址

一、Python软件下载地址 1. 官网下载 https://www.python.org/downloads/ 2. 国内第三方镜像 https://mirrors.huaweicloud.com/python/ https://registry.npmmirror.com/binary.html?pathpython/ 从以上国内镜像即可下载安装程序&#xff0c;Windows平台&#xff0c;不论是In…

网络安全 DVWA通关指南 DVWA File Inclusion(文件包含)

DVWA File Inclusion&#xff08;文件包含&#xff09; 文章目录 DVWA File Inclusion&#xff08;文件包含&#xff09;本地文件包含(LFI)漏洞利用 远程文件包含(RFL)漏洞利用 修复建议 LowMediumHighImpossible 本地文件包含(LFI) 文件包含漏洞的产生原因是 PHP 语言在通过引…

我的世界 异地联机教程 无需公网IP、服务器

主要内容 什么是Minecraft&#xff08;JAVA国际版&#xff09; 搭建该服务&#xff0c;需要准备什么 详细步骤 1.启动器 安装MC并运行MC 2.运行 MoleSDN 进行异地联机 3.小伙伴皮蛋加入鼠鼠的MC 完成联机 什么是我的世界 一款3D沙盒电子游戏&#xff0c;由Mojang Studio…

ComfyUI大猫咪写真工作流,哩布线上一键运行

前言 这次教程是用ComfyUI做的大猫咪写真。 视频教程 打开下面这个网站&#xff0c;点击【在线运行工作流】就可以一键运行ComfyUI工作流了 所有的AI设计工具&#xff0c;模型和插件&#xff0c;都已经整理好了&#xff0c;&#x1f447;获取~ 正面关键词&#xff1a; Chin…

基于二叉树的近似最近邻搜索-Annoy

在推荐系统的召回阶段&#xff0c;会实时计算用户的表征向量&#xff08;user/query&#xff09;&#xff0c;然后去物料库去寻找与用户最匹配的N个物料返回给用户&#xff1b;在搜索系统&#xff0c;也同样存在这样的需求&#xff0c;用户的搜素&#xff08;query&#xff09;…

Efficient DETR:别再随机初始化了,旷视提出单解码层的高效DETR | CVPR 2021

Efficient DETR结合密集检测和稀疏集合检测的优点&#xff0c;利用密集先验来初始化对象容器&#xff0c;弥补单层解码器结构与 6 层解码器结构的差距。在MS COCO上进行的实验表明&#xff0c;仅 3 个编码器层和 1 个解码器层即可实现与最先进的目标检测方法竞争的性能&#xf…

指针函数与函数指针的区别

1、指针函数 1-1、定义 指针函数&#xff0c;顾名思义&#xff0c;是一个函数&#xff0c;但其返回类型是指针。这意味着当这个函数被调用时&#xff0c;它会返回一个地址值&#xff0c;这个地址值指向某个类型的数据。 1-2、特点 函数性质&#xff1a;首先&#xff0c;它是…

【2024】20个高级 Java 面试问题及答案

1&#xff1a;解释Java序列化中transient关键字的意义。 在 Java 中&#xff0c;“ transient ”关键字用于指示变量在对象序列化期间不应被序列化。当变量被标记为“transient”时&#xff0c;意味着该变量应被序列化机制忽略。 这在处理不应持久的敏感或临时数据时特别有用…

基础 - 前端知识体系详解

一、前端三要素 HTML&#xff08;结构&#xff09;&#xff1a; 超文本标记语言&#xff08;Hyper Text Markup Language&#xff09;&#xff0c;决定网页的结构和内容。CSS&#xff08;表现&#xff09;&#xff1a; 层叠样式表&#xff08;Cascading Style Sheets&#xff0…

基于飞腾平台的Hbase的安装配置

【写在前面】 飞腾开发者平台是基于飞腾自身强大的技术基础和开放能力&#xff0c;聚合行业内优秀资源而打造的。该平台覆盖了操作系统、算法、数据库、安全、平台工具、虚拟化、存储、网络、固件等多个前沿技术领域&#xff0c;包含了应用使能套件、软件仓库、软件支持、软件适…

人脸操作:从检测到识别的全景指南

人脸操作&#xff1a;从检测到识别的全景指南 在现代计算机视觉技术中&#xff0c;人脸操作是一个非常重要的领域。人脸操作不仅包括检测图像中的人脸&#xff0c;还涉及到人脸识别、表情分析、面部特征提取等任务。这些技术在各种应用中发挥着关键作用&#xff0c;从社交媒体…

Windows Server 2016 Standard 将程序加入开机自启动

分3步 1 打开“启动”文件夹&#xff1a;在Windows的搜索栏中输入“shell:startup”&#xff0c;点击搜索结果中的 “启动” 文件夹即可打开。 2 在启动文件夹中&#xff0c;右键点击空白区域&#xff0c;选择“新建”->“快捷方式”。 3 将 “程序的快捷方式” 添加到启动…

IP转地理位置:3个好用免费开源库代码及数据库对比体验详解

最近在做一个IP定位显示国家省市功能&#xff0c;在全网找了一圈&#xff0c;也每个安装体验过&#xff0c;测试他的数据库精准度。 本人是用PHP的第三方库&#xff0c;整理以下使用过的ip定位转地理位置库。 ip定位转地理位置库 1.itbdw/ip-database&#xff1a; **gihub地…

Qt 系统相关 - 网络与音视频

目录 一、Qt 网络 1. UDP Socket 1.1 核心 API 概览 1.2 回显服务器 1.3 回显客户端 2. TCP Socket 2.1 核心 API 概览 2.2 回显服务器 2.3 回显客户端 3. HTTP Client 3.1 核心 API 3.2 代码示例 二、Qt 音视频 1. Qt 音频 1.1 核心API概览 1.2 示例 2. Qt 视…

Java面试八股之请简述消息队列的发布订阅模式

请简述消息队列的发布订阅模式 发布订阅&#xff08;Publish-Subscribe&#xff0c;简称 Pub/Sub&#xff09;模型是一种消息传递模式&#xff0c;它在组件之间提供了高度的解耦和灵活性。这种模式广泛应用于分布式系统、事件驱动架构以及消息队列系统中。下面是发布订阅模型的…