Android studio 进行网络连接时,出现 HttpResponse reponse =new DefaultHttpClient().execute(request)处有错误时,一般有两种可能:
1、没有在AndroidManifest.xml中添加网络权限:
<uses-permission android:name="android.permission.INTERNET" />
2、没有在activity函数中添加Exception()函数:
public void Exception(){ //避免出现android.os.NetworkOnMainThreadException异常 StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectDiskReads().detectDiskWrites().detectNetwork() .penaltyLog().build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectLeakedSqlLiteObjects().detectLeakedClosableObjects() .penaltyLog().penaltyDeath().build()); }具体加在界面onCreate(Bundle savedInstanceState)初始化函数中,即
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login_aty); Exception();//避免出现android.os.NetworkOnMainThreadException异常 ............... ............... }