• 关于Http请求出现NetworkOnMainThreadException。


      连不上网并不是一定Ip,tomcat错误,因为在Android4.0以后,只要是写在主线程(就是Activity)中的HTTP请求,运行时都会下面这样错,这是因为Android在4.0以后为了防止应用的ANR(aplication Not Response)异常。

    java.lang.RuntimeException: Unable to start activity ComponentInfo

    android.os.NetworkOnMainThreadException 

       有两种解决的方法:

    1.可以再Activity的onCreate()方法中加入这样一段代码,如下:

      if (Build.VERSION.SDK_INT >= 11) {
          StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads    ().detectDiskWrites().detectNetwork().penaltyLog().build());
       StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());
      }

    后就可以在主线程中进行网络操作了;

    2.但是我们应该这样做

      启动一条子线程进行你的网络请求。

     

    建议使用第二种方法,养成规范的习惯;

     示例:

    package com.example.postandroid;
    
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.util.ArrayList;
    import java.util.List;
    
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.util.EntityUtils;
    
    import com.example.postandroid.R.id;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.widget.TextView;
    
    public class MainActivity extends Activity {
        private TextView show;
        private String URL = "http://192.168.156.1/lyl/android.jsp";
        private boolean flag = false;
    
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            show = (TextView) findViewById(id.show);
            Thread thread = new Thread(null, threadInBack, "HttpRequest");
           //启动线程 
        thread.start(); }
    private Runnable threadInBack = new Runnable() { public void run() { httpRequest(); } private void httpRequest() { HttpPost httpPost = new HttpPost(URL); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("id", "lyl")); params.add(new BasicNameValuePair("password", "123")); try { httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); HttpResponse httpResponse = new DefaultHttpClient() .execute(httpPost); if (httpResponse.getStatusLine().getStatusCode()!= 404) { flag = Boolean.parseBoolean(EntityUtils.toString( httpResponse.getEntity()).trim()); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if(flag){ show.setText("登陆成功"); }else{ show.setText("登陆失败"); } } }; @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
  • 相关阅读:
    微信公众号-框架业务
    微信公众号-加解密数据demo坑
    JS进制转换,浮点数相加,数字判断
    lamp环境-编译安装
    批量解压目录下的文件
    设置用户sudo -s拥有root权限
    CentOS 6.5-默认没开启网络连接:开启网络连接
    检查一下是否安装了环境,安装则卸载
    负载均衡-多台机子session不起效:把php.ini中file改为memcache存储
    由json生成php配置文件
  • 原文地址:https://www.cnblogs.com/mydomainlistentome/p/4701617.html
Copyright © 2020-2023  润新知