Android客户端与服务器端交换之客户端

xml文件就不放出来了,就是一个输入账号,输入密码,再来三个按钮,登录,重置,注册

下面贴出我的java代码部分

LoginToServer

package com.example.loginandregister;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class LoginToServer {

	String urlAddress = "";//服务器端地址
	//以get方式来发送请求
	public String doGet(String username, String password){
		
		String getUrl = urlAddress + "?username=" + username + "&password=" + password;//拼接地址
		
		HttpGet httpGet = new HttpGet(getUrl);
		
		HttpClient hc = new DefaultHttpClient();
		
		try {
			
			HttpResponse ht = hc.execute(httpGet); // 给客户端一个响应

			HttpEntity he = ht.getEntity(); // 内容
			InputStream is = he.getContent();
			BufferedReader br = new BufferedReader(new InputStreamReader(is,
					"GBK"));
			
			String response = "";
			String readLine = null;
			while ((readLine = br.readLine()) != null) {
				response = response + readLine;
			}
			is.close();

			return response;
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			return "exception";
		} catch (IOException e) {
			e.printStackTrace();
			return "exception";
		}
	}
	public String doPost(String username, String password){
		HttpPost httpPost = new HttpPost(urlAddress);
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		NameValuePair pair1 = new BasicNameValuePair("username", username);
		NameValuePair pair2 = new BasicNameValuePair("password", password);
		params.add(pair1);
		params.add(pair2);
		HttpEntity he;
		try {
			he = new UrlEncodedFormEntity(params, "gbk");
			httpPost.setEntity(he);
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}

		HttpClient hc = new DefaultHttpClient();
		try {
			HttpResponse ht = hc.execute(httpPost);
			if (ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				HttpEntity het = ht.getEntity();
				InputStream is = het.getContent();
				BufferedReader br = new BufferedReader(
						new InputStreamReader(is));
				String response = "";
				String readLine = null;
				while ((readLine = br.readLine()) != null) {
					response = response + readLine;
				}
				is.close();
				return response;
			} else {
				return "error";
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			return "exception";
		} catch (IOException e) {
			e.printStackTrace();
			return "exception";
		}

	}
}

LoginActivity

package com.example.loginandregister;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends Activity {

	private EditText name,password;
	private Button login,reset,register;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO 自动生成的方法存根
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		
        name = (EditText) findViewById(R.id.name);
		password = (EditText) findViewById(R.id.psd);
		login = (Button) findViewById(R.id.login);
		reset = (Button) findViewById(R.id.reset);
		register=(Button)findViewById(R.id.register);
		
		login.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO 自动生成的方法存根
				final Handler myHandler=new Handler(){					
					public void handleMessage(Message msg) {
						boolean b=(Boolean)msg.obj;
						if(b){
							Intent intent=new Intent(LoginActivity.this,MainActivity.class);
							Bundle bundle=new Bundle();
							bundle.putString("name", name.getText().toString());
							bundle.putString("psd", password.getText().toString());
							intent.putExtras(bundle);
							startActivity(intent);
							finish();
							Toast.makeText(LoginActivity.this, "登录成功", 1000).show();
						}else{
							Toast.makeText(LoginActivity.this, "登录失败", 1000).show();
						}
					}
				};
				new Thread(){
					public void run() {
						boolean b=checkUser(name.getText().toString(),password.getText().toString());						
						Message message=new Message();
						message.obj=b;
						myHandler.sendMessage(message);
					}
				}.start();	
			}
		});
		reset.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				name.setText("");
				password.setText("");
			}
		});
		register.setOnClickListener(new OnClickListener() {			
			public void onClick(View v) {
				Intent intent=new Intent(LoginActivity.this,RegisterActivity.class);
				startActivity(intent);
				finish();
			}
		});
	}
	public boolean checkUser(String name, String psd) {		
		LoginToServer loginToServer = new LoginToServer();
		String response = loginToServer.doGet(name, psd);		
		if ("true".equals(response)) {
			return true;
		} else {
			return false;
		}
	}
}

RegisterToServer

package com.example.loginandregister;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class RegisterToServer {

	String urlAddress = "";//服务器端地址
	//以Get方式发送请求
	public String doGet(String username, String password) {
		String getUrl = urlAddress + "?username=" + username + "&password=" + password;//拼接地址	
		HttpGet httpGet = new HttpGet(getUrl);
		HttpClient hc = new DefaultHttpClient();		
		try {
			HttpResponse ht = hc.execute(httpGet); // 给客户端一个响应
			System.out.println("ht=" + ht);
			HttpEntity he = ht.getEntity(); // 内容
			InputStream is = he.getContent();
			BufferedReader br = new BufferedReader(new InputStreamReader(is,
					"GBK"));
			String response = "";
			String readLine = null;
			while ((readLine = br.readLine()) != null) {
				response = response + readLine;
			}
			is.close();
			return response;
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			return "exception";
		} catch (IOException e) {
			e.printStackTrace();
			return "exception";
		}
	}
	//以post形式发送请求
	public String doPost(String username, String password) {
		HttpPost httpPost = new HttpPost(urlAddress);
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		NameValuePair pair1 = new BasicNameValuePair("username", username);
		NameValuePair pair2 = new BasicNameValuePair("password", password);
		params.add(pair1);
		params.add(pair2);
		HttpEntity he;
		try {
			he = new UrlEncodedFormEntity(params, "gbk");
			httpPost.setEntity(he);
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		HttpClient hc = new DefaultHttpClient();
		try {
			HttpResponse ht = hc.execute(httpPost);
			if (ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				HttpEntity het = ht.getEntity();
				InputStream is = het.getContent();
				BufferedReader br = new BufferedReader(
						new InputStreamReader(is));
				String response = "";
				String readLine = null;
				while ((readLine = br.readLine()) != null) {
					response = response + readLine;
				}
				is.close();
				return response;
			} else {
				return "error";
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			return "exception";
		} catch (IOException e) {
			e.printStackTrace();
			return "exception";
		}

	}
}

RegisterActivity

package com.example.loginandregister;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class RegisterActivity extends Activity {

	private EditText name, psd, repsd;
	private Button reset, register;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO 自动生成的方法存根
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register);
		
		name = (EditText) findViewById(R.id.name);
		psd = (EditText) findViewById(R.id.psd);
		repsd = (EditText) findViewById(R.id.repsd);
		reset = (Button) findViewById(R.id.reset);
		register = (Button) findViewById(R.id.register);
		reset.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				name.setText("");
				psd.setText("");
				repsd.setText("");
			}
		});
		register.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				String checkResult = checkInfo();
				if (checkResult != null) {
					Builder builder = new AlertDialog.Builder(
							RegisterActivity.this);
					builder.setTitle("出错提示");
					builder.setMessage(checkResult);
					builder.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									psd.setText("");
									repsd.setText("");
								}
							});
					builder.create().show();
				} else {
					final Handler myHandler = new Handler() {
						public void handleMessage(Message msg) {
							boolean b = (Boolean) msg.obj;
							if (b) {
								Intent intent = new Intent(
										RegisterActivity.this,
										LoginActivity.class);
								startActivity(intent);
								Toast.makeText(RegisterActivity.this, "注册成功",
										1000).show();
								finish();
							} else {
								Toast.makeText(RegisterActivity.this, "注册失败",
										1000).show();
							}
						}
					};
					new Thread() {
						public void run() {
							boolean b = false;
							RegisterToServer registerToServer = new RegisterToServer();
							String response = registerToServer.doGet(name
									.getText().toString(), psd.getText()
									.toString());
							if ("true".equals(response)) {
								b = true;
							} else {
								b = false;
							}
							Message message = new Message();
							message.obj = b;
							myHandler.sendMessage(message);
						}
					}.start();
				}
			}
		});
	}
		public String checkInfo() {
			if (name.getText().toString() == null
					|| name.getText().toString().equals("")) {
				return "用户名不能为空";
			}
			if (psd.getText().toString().trim().length() < 3
					|| psd.getText().toString().trim().length() > 15) {
				return "密码位数应该3~15之间";
			}
			if (!psd.getText().toString().equals(repsd.getText().toString())) {
				return "两次输入的密码不一致";
			}
			return null;
		}
	}

MainActivity

package com.example.loginandregister;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}
}

这只是一个最简单的链接数据库的操作的客户端的写法,其中的一些判断也只是最基本的一些判断!

笔记 2014-03-28


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值