Android向Web服务器发送Post请求并返回数据

来源:互联网 发布:ubuntu 系统log 编辑:程序博客网 时间:2024/04/30 14:42

1.android 向web服务器发送post请求并获取结果,因为 需要访问到网络必须要有权限,先在AndroidManifest.xml中加入如下配置:

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

2.发送post请求并获取结果的activity 代码如下(结果返回1(成功)或-1(失败0)):

  btnOK.setOnClickListener(new OnClickListener(){    @Overridepublic void onClick(View view) {String url="http://192.168.123.7:8900/Login.aspx";HttpPost httpRequest=null;List<NameValuePair> params=null;HttpResponse httpResponse=null;//建立HttpPost链接httpRequest=new HttpPost(url);//Post操作参数必须使用NameValuePair[]阵列储存params=new ArrayList<NameValuePair>();params.add(new BasicNameValuePair("domain",domain.getText().toString()));params.add(new BasicNameValuePair("uid",uid.getText().toString()));params.add(new BasicNameValuePair("pwd",pwd.getText().toString()));try{   //发送Http RequesthttpRequest.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));    //取得Http ResponsehttpResponse=new DefaultHttpClient().execute(httpRequest);//若状态码为200if(httpResponse.getStatusLine().getStatusCode()==200)    {//获得返回的数据    String strResult=EntityUtils.toString(httpResponse.getEntity());     if(strResult.equalsIgnoreCase("1"))     {    // openDialog("登入成功!");new AlertDialog.Builder(Login.this).setTitle("提示").setMessage("登入成功!").setPositiveButton("确定",new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface arg0, int arg1) {// 跳转到另一个Acitivity并传值Intent intent=new Intent();intent.putExtra("curUserId",domain.getText().toString()+"/"+ uid.getText().toString());    intent.setClass(Login.this, Holiday.class);    Login.this.startActivity(intent);}}).show();      }     else if(strResult.equalsIgnoreCase("0"))     {     openDialog("您输入的信息有误!");         }    }else{openDialog("Error!");        }}catch(Exception e){e.printStackTrace();}}});