1.网络请求不能在主线程中执行
安卓在SDK3以上不允许在主线程中执行网络操作,防止在网络阻塞的情况下造成应用僵死
官方解释:
Class Overview
The exception that is thrown when an application attempts to perform a networking operation on its main thread. This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged. See the document Designing for Responsiveness.
Also see StrictMode.
目前我知道有两种解决方案
(1).直接暴力修改模式策略
在MainActivity文件的setContentView(R.layout.activity_main)下面加上如下代码:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);当然这是非常不推荐的
(2).另开一个线程
将请求网络资源的代码使用Thread去操作,在Runnable中做HTTP请求,不用阻塞UI线程。
new Thread(new Runnable(){
@Override
public void run() {
//网络相关操作
}
}).start()2.安卓9以上HTTP问题
Google表示,为保证用户数据和设备的安全,针对下一代 Android 系统(Android P) 的应用程序,将要求默认使用加密连接,这意味着 Android P 将禁止 App 使用所有未加密的连接,因此运行 Android P 系统的安卓设备无论是接收或者发送流量,未来都不能明码传输,需要使用下一代(Transport Layer Security)传输层安全协议,而 Android Nougat 和 Oreo 则不受影响。
所以如果在P及以上安卓系统中用HttpURLConnection来执行http请求时会产生如下的异常:
java.io.IOException: Cleartext HTTP traffic to **** not permitted
目前有以下三种解决方案:
- 改用https请求
- targetSdkVersion降到27以下
- 在res目录下新建一个xml目录,然后新建network_security_config.xml:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true" />
</network-security-config>然后再AndroidManifest.xml的application标签下增加一个属性:
<application
...
android:networkSecurityConfig="@xml/network_security_config"
...
/>这样就可以发送http请求了。