Android开发 HttpURLConnection请求互联网资源失败问题

编程入门 行业动态 更新时间:2024-10-27 12:24:01

项目场景:

Android开发 HttpURLConnection请求互联网资源失败问题


问题描述

Android高版本联网失败报错:Cleartext HTTP traffic to xxxx not permitted以及不能够在主线程请求网络资源的问题。

try{
            qwe++;
            String str = "http://49.235.134.191:8080/news/get";
            URL url = new URL(str);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            if(connection.getInputStream() != null)
            qwe+=10;
            else qwe += 20;
            InputStream is = connection.getInputStream();
            qwe++;
            br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String s = null;
            while ((s = br.readLine()) != null){
                sb.append(s);qwe++;
            }
            Log.i("qw", "getUrlData: sb1--"+sb.toString() );
            br.close();
        }catch (Exception e){System.out.println("异常为:");
            e.printStackTrace();

        }finally {
            if (connection != null){
                connection.disconnect();
            }
        }

原因分析:

1.Google针对新一代 Android 系统将要求默认使用加密连接,因此http请求未加密互联网资源失败,https则可以成功。
2.不能在主线程请求网络资源


解决方案:

针对不能请求未加密连接,在AndroidManifest.xml配置文件的标签中直接插入(感谢junbs分享)

    android:usesCleartextTraffic="true"

针对不能在主线程请求网络资源,在Oncreate下插入如下代码(参考https://blog.csdn/kaiqiangzhang001/article/details/8350938)

    StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

更多推荐

Android开发 HttpURLConnection请求互联网资源失败问题

本文发布于:2023-06-13 21:51:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1408891.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:互联网   资源   Android   HttpURLConnection

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!