org.apache.http.conn.HttpHostConnectException: Connection to refused

android出现这个问题:

http://www.oschina.net/code/snippet_12_5909


private void dopost(String val){
     //封装数据
     Map<String, String> parmas = new HashMap<String, String>();
     parmas.put("name", val);
    
     DefaultHttpClient client = new DefaultHttpClient();//http客户端
     HttpPost httpPost = new HttpPost("http://mhycoe.com/test/post.php");
    
     ArrayList<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
     if(parmas != null){
         Set<String> keys = parmas.keySet();
         for(Iterator<String> i = keys.iterator(); i.hasNext();) {
              String key = (String)i.next();
              pairs.add(new BasicNameValuePair(key, parmas.get(key)));
         }
    }
    
  try {
   UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(pairs, "utf-8");
         /*
          *  将POST数据放入HTTP请求
          */
         httpPost.setEntity(p_entity);
         /*
          *  发出实际的HTTP POST请求
           */
         HttpResponse response = client.execute(httpPost);
         HttpEntity entity = response.getEntity();
         InputStream content = entity.getContent();
   String returnConnection = convertStreamToString(content);
         show.setText(returnConnection);
  } catch (IllegalStateException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
    
 }

  private String convertStreamToString(InputStream is) {
   BufferedReader reader = new BufferedReader(new InputStreamReader(is));
         StringBuilder sb = new StringBuilder();
         String line = null;
         try {
              while ((line = reader.readLine()) != null) {
                   sb.append(line);
              }
         } catch (IOException e) {
              e.printStackTrace();
         } finally {
              try {
                   is.close();
              } catch (IOException e) {
                   e.printStackTrace();
              }
         }
         return sb.toString();
 }

解决方法,加权限!!


<uses-permission android:name="android.permission.INTERNET"/>




如果用接着出现异常android.os.NetworkOnMainThreadException

参考

http://www.cnblogs.com/freexiaoyu/archive/2012/04/13/2445707.html


注意:造成这样的错误原因是代码不符合Android规范,如果把上面访问方式改为异步操作就不会出现在4.0上访问出现 android.os.NetworkOnMainThreadException异常

 如:

new Thread(){
@Override
public void run(){
//你要执行的方法
//执行完毕后给handler发送一个空消息
handler.sendEmptyMessage(0);
}
}.start();

 

//定义Handler对象
private Handler handler =new Handler(){
@Override
//当有消息发送出来的时候就执行Handler的这个方法
public void handleMessage(Message msg){
super.handleMessage(msg);
//处理UI
}
};







  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 11
    评论
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值