首页 > 其他分享 >【安卓】WebView的用法与HTTP访问网络

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

时间:2024-08-15 19:24:36浏览次数:10  
标签:HTTP void response public connection reader new WebView 安卓

文章目录


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

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,void,response,public,connection,reader,new,WebView,安卓
From: https://blog.csdn.net/qq_47658735/article/details/141230049

相关文章

  • go写的http工具
    gobuildreverseProxy.goreverseProxyhttp://192.168.50.148:123212024/08/1515:14:47programstart......2024/08/1515:14:47listenhttpproxyon:8001.....浏览器中输入:http://127.0.0.1:8001/,即可访问指定网站,并打印http请求与返回数据包。packagemainimport("byt......
  • 安卓手机被偷偷安装下载App?也许问题在这里
    自己的安卓手机,设置中所有的未知来源安装已经设置为不允许,单个应用安装第三方和自动更新也已关闭,但是有一天在微博上突然还是遇到了难以关闭的强制页面和偷偷直接安装了很多推广应用, 百思不得其解,终于还是要打算研究下到底怎么回事?首先,在设置中安装未知来源这个选项下的应用......
  • 【安卓】Service生命周期与前台活动
    文章目录Service生命周期使用前台Service前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站。Service生命周期  在项目的任何位置调用了Context的startService()方法,相应的Service就会启动,并回调onStartCommand(......
  • 给安卓 app 添加权限的一种方法
    依赖两个app官方文档一个是Shizuku,可以直接安装另一个是AppOps,需要通过adb安装#通过adb启动Shizuku服务adbshellsh/sdcard/Android/data/moe.shizuku.privileged.api/start.sh#安装AppOpsadbinstall-i'com.android.vending'appops-v9.0.7.r1708.5......
  • 计算机网络——HTTP协议详解(上)
    一、HTTP协议简单介绍1.1什么是HTTP协议HTTP(超文本传输协议)是一种用于在Web浏览器和Web服务器之间传输数据的应用层协议。它是一种无状态协议,即服务器不会保留与客户端的任何连接状态信息,每个请求都被视为一个独立的事务。假设你使用Web浏览器(例如Chrome)访问一个网页。当......
  • HTTP请求走私
    http请求走私 Conent-LengthConent-Length表示实体内容长度,当客户端向服务器请求一个静态页面或者一张图片时,服务器可以很清楚的知道内容大小,然后通过Content-length消息首部字段告诉客户端需要接收多少数据。Transfer-Encoding分块编码,数据分解成一系列数据块,并以一个或多......
  • Golang httputil 包深度解析:HTTP请求与响应的操控艺术
    标题:Golanghttputil包深度解析:HTTP请求与响应的操控艺术引言在Go语言的丰富标准库中,net/http/httputil包是一个强大的工具集,它提供了操作HTTP请求和响应的高级功能。从创建自定义的HTTP代理到调试HTTP流量,httputil包都能提供必要的支持。本文将深入探讨httputil包的功能......
  • https原理
    目录一、HTTPS的实现原理1.证书验证阶段:2.数据传输阶段:二、为什么数据传输是用对称加密?三、为什么需要CA认证机构颁发证书?1.过程原理如下:四、浏览器是如何确保CA证书的合法性?1.证书包含什么信息?2.证书的合法性依据是什么?3.浏览器如何验证证书的合法性?4.只有认证机......
  • uniapp+uView安卓与IOS微信与支付宝支付
    页面仅供参考,记录支付流程处理方法:<template> <viewclass="pay-order-page">  <viewclass="content-box"style="padding-bottom:14rpx;">   <viewclass="tip-box"v-if="detail.purchaseLimitNum>0&qu......
  • npm报错:request to https://registry.npm.taobao.org failed处理办法
    今天在安装flowise的时候提示npm报错:requestto https://registry.npm.taobao.org failed,reasoncertificatehasexpired看提示是淘宝镜像过期了。找了一下资料,好像是npm淘宝镜像已经从 registry.npm.taobao.org 切换到了 registry.npmmirror.com。旧域名也将于2022......