public class Http {
  public HttpClient httpClient ;  
    public String getRequest(String url)  
        throws Exception  
    {  
        httpClient= new DefaultHttpClient();  
          
        try{  
            // 创建HttpGet对象。  
            HttpGet get = new HttpGet(url);  
         //HttpUriRequest get=new HttpGet(url);
            // 发送GET请求  
            HttpResponse httpResponse = httpClient.execute(get);  
            // 如果服务器成功地返回响应  
            if (httpResponse.getStatusLine()  
                .getStatusCode() == 200)  
            {  
                // 获取服务器响应字符串  
                String result = EntityUtils  
                    .toString(httpResponse.getEntity(),"GBK");  
                return result;  
            }  
        }catch(Exception e){  
              
            e.printStackTrace();  
            return "获取数据失败!";  
        }finally{  
            httpClient.getConnectionManager().shutdown();  
        }  
  
        return null;  
    }  
  
    /** 
     *  
     * @param url 发送请求的URL 
     * @param params 请求参数 
     * @return 服务器响应字符串 
     * @throws Exception 
     */  
    public String postRequest(String url, Map<String ,String> rawParams)  
    {  
        httpClient= new DefaultHttpClient();  
        try{  
            // 创建HttpPost对象。  
            HttpPost post = new HttpPost(url);  
            // 如果传递参数个数比较多的话可以对传递的参数进行封装  
            List<NameValuePair> params = new ArrayList<NameValuePair>();  
            for(String key : rawParams.keySet())  
            {  
                //封装请求参数  
                params.add(new BasicNameValuePair(key , rawParams.get(key)));  
            }  
            // 设置请求参数  
            post.setEntity(new UrlEncodedFormEntity(  
                params,HTTP.UTF_8));  
            // 发送POST请求  
            HttpResponse httpResponse = httpClient.execute(post);  
            System.out.println("f");
            // 如果服务器成功地返回响应  
            if (httpResponse.getStatusLine()  
                .getStatusCode() == 200)  
            {  
                // 获取服务器响应字符串  
                String result = EntityUtils  
                    .toString(httpResponse.getEntity(),"UTF-8");  
                
                return result;  
            }  
        }catch(Exception e){  
            e.printStackTrace();  
        }finally{  
            httpClient.getConnectionManager().shutdown();  
        }  
        return null;  
    }  
    }
 http请求的  在android2.3一下都没问题  可以获取到网络信息  倒是在4.0上就获取不到 
大神们看看是怎么回事

解决方案 »

  1.   

    4.0强制strictMode了,是从Android 3.0开始的
    必须将HTTP请求放到线程中也可以在Activity的OnCreate中去掉StrictMode
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
     
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);  
    }
    但最好是用线程,asyncTask也挺简单的具体看看这吧,http://www.bcoder.com/?p=37