android读取URL链接内容

利用Scanner读取

/**
     * 获取URL中字符串
     *
     * @param url 网址字符串
     * @return String 网页内容
     */
    public String getHttpsContent(String url) {
        //利用java Scanner从URL读取Content
        String httpsContent = null;
        try {
            Scanner scanner = new Scanner(new URL(url).openStream(), StandardCharsets.UTF_8.toString());
            scanner.useDelimiter("\\A");
            if (scanner.hasNext()) {
                httpsContent = scanner.next();
            }
            scanner.close();
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        if (httpsContent != null) {
            Log.i(getClass().toString() + "//getHttpsContent()", httpsContent);
        }
        return httpsContent;
    }

在这之前可以判断一下网络通不通

/**
     * 是否联网
     *
     * @param context ()
     * @return boolean 是否联网
     */
    public boolean isNetworkAvailable(Context context) {
        if (context != null) {
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected()) {
                Log.d(getClass().toString() + "//isNetworkAvailable()", "TRUE");
                return true;
            }
        }
        Log.d(getClass().toString() + "//isNetworkAvailable()", "FALSE");
        return false;
    }

调用的时候判断一下连上网没有然后进行数据处理

if (isNetworkAvailable(getApplicationContext())) {
                    do_something();
                   
                } else {
                    Toast.makeText(getBaseContext(), "网络不可用", Toast.LENGTH_SHORT).show();
                }

注意:网络方面的处理一定一定一定放在子线程处理,避免anr

new Thread(() -> {
                Looper.prepare();
                if (isNetworkAvailable(getApplicationContext())) {
                   do_something();
                    }
                } else {
                    Toast.makeText(getBaseContext(),"网络不可用" , Toast.LENGTH_SHORT).show();
                }
                Looper.loop();
            }).start();

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值