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

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

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

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

  btnOK.setOnClickListener(new OnClickListener(){
    	
		@Override
		public 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 Request
				httpRequest.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
			    //取得Http Response
				httpResponse=new DefaultHttpClient().execute(httpRequest);
				//若状态码为200
				if(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() {
							@Override
							public 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();
			}
		}});


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值