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