当前位置: 代码迷 >> Android >> apache的HttpClient 执行总是错误,
  详细解决方案

apache的HttpClient 执行总是错误,

热度:16   发布时间:2016-05-01 14:49:57.0
apache的HttpClient 执行总是异常,求助啊!
HttpClient httpClient = new DefaultHttpClient(); 
HttpGet httpGet = new HttpGet("http://www.baidu.com/");
  try{
  HttpResponse response = httpClient.execute(httpGet);
  }
  catch(Exception e){
  System.out.println("<-------Exception------->");
  e.printStackTrace();
  }

执行到红色那句话时出异常,走到catch下面去了。异常如下:
08-22 14:25:22.784: W/System.err(8976): android.os.NetworkOnMainThreadException
08-22 14:25:22.784: W/System.err(8976): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
08-22 14:25:22.784: W/System.err(8976): at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
08-22 14:25:22.784: W/System.err(8976): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
08-22 14:25:22.784: W/System.err(8976): at java.net.InetAddress.getAllByName(InetAddress.java:220)
08-22 14:25:22.784: W/System.err(8976): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
08-22 14:25:22.784: W/System.err(8976): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
08-22 14:25:22.784: W/System.err(8976): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
08-22 14:25:22.784: W/System.err(8976): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)

对HTTP这块不是很熟,我查阅了很多资料和书籍,代码都是这样写的,也有在网络上问过类似的问题,但是都没有一个好的解答,求高手点拨,谢谢~!


------解决方案--------------------
NetworkOnMainThreadException
提示你不要在主线程中访问网络。

把要访问的网络单独放在一个线程中:
Java code
new Thread(){    @Override    public void run()    {        HttpClient httpClient = new DefaultHttpClient();          HttpGet httpGet = new HttpGet("http://www.baidu.com/");        try        {            HttpResponse response = httpClient.execute(httpGet);        }        catch(Exception e)        {            System.out.println("<-------Exception------->");            e.printStackTrace();        }           }}.start();
------解决方案--------------------
Android好像是从3.0还是4.0版本开始强制要求网络操作不能在主线程进行,像楼上一样,另开一个线程就OK了
  相关解决方案