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

项目场景:

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.net/kaiqiangzhang001/article/details/8350938)

    StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值