您的位置:首页 > 理论基础 > 计算机网络

android 客户端数据传递之二:基于Http协议获取数据 代码

2012-07-07 22:54 736 查看
http://sizeed.blog.163.com/blog/static/965254512011102145327434/

这里需要注意的是模拟器把自己当成了localhost,以及127.0.0.1了,因此如果基于本地的web项目测试的话,必须修改IP为:10.0.2.2

public class TestPostHtml extends Activity {   
 /** Called when the activity is first created. */
 //模拟器自己把自己当成localhost了,服务器应该为10.0.2.2
 private static  String url="http://110.80.10.194:11000/p.php";
 
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  getPDAServerData(url);    
  }
 /**     * 请求服务     * @param url     */
 private void getPDAServerData(String url){
  url+="?username=123456";    
  HttpClient client=new DefaultHttpClient();
  HttpPost request;     
  try {     
   request = new HttpPost(new URI(url));
   HttpResponse response=client.execute(request);   //判断请求是否成功     
   if(response.getStatusLine().getStatusCode()==200){
    HttpEntity  entity=response.getEntity();   
    if(entity!=null){   
     //String out=EntityUtils.toString(entity).getBytes("utf-8").toString();
     String out=new String(EntityUtils.toString(entity).getBytes("ISO8859-1"),"utf-8");
     Log.i("显示数据",""+out);
     new AlertDialog.Builder(this).setMessage(out).create().show();   
     }     
    }    
   }catch (URISyntaxException e) {
    e.printStackTrace();
    Log.i("URISyntaxException",""+e);
    }    
   catch (ClientProtocolException e) {
    e.printStackTrace(); 
    Log.i("ClientProtocolException",""+e);
   } catch (IOException e) {
    e.printStackTrace(); 
   }   
  }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐