android 学习笔记

android模拟器(simulator)把它自己作为了localhost,也就是说,代码中使用localhost或者127.0.0.1来访问,都是访问模拟器自己!这是不行的!

如果你想在模拟器simulator上面访问你的电脑,那么就使用android内置的IP 10.0.2.2 吧,  10.0.2.2 是模拟器设置的特定ip,是你的电脑的别名alias

记住,在模拟器上用10.0.2.2访问你的电脑本机

 

android http post  实现

 

  public void onClick(View v) {
    dopost(txt.getText().toString());
    
   }
  });
    }

 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();
 }
}

评论 (2)
  1. avatar
    沙发
    黎川奇侠 2010-10-17 06:10

    看不懂!汗

  2. avatar
    板凳
    大猪 2010-10-22 05:34

    一直想买个adnroid手机呢,不知道这玩意是用什么语言开发的

    浩忍 于 10/25/2010 9:23:28 AM 回复

    应用软件是用Java! 我也想买个android 手机。就是没钱 哈哈