http://www.android100.org/html/201406/09/22915.html
1.服务器端
服务器端和android没有太大关系,对J2EE比较熟悉的话写起来应该很容易,这里就不一一贴出代码。
首先在本地创建一个数据库表,其中包含了一个userinfo表用来存储用户信息。
需要实现的代码如下:
DBUtils:创建数据库连接对象
User实体类:用来存放用户信息
UserDao:用来对处理User相关的数据操作
UserService:调用UserDao来处理事务
UserServlet:处理用户请求,并返回
当客户端访问该servlet时,获得客户端传入的数据,处理数据,并将结果写到response中返回给客户端。
UserServlet中doPost方法如下:
[java] <span style="font-size:16px;">1 public void doPost(HttpServletRequest request, HttpServletResponse response)
2 throws ServletException, IOException {
3 UserService us = UserService.getInstance();
4 String username = request.getParameter("username"); //获得从客户端传入的用户名和密码
5 String password = request.getParameter("password");
6 //System.out.println("username:"+username);
7 //System.out.println("password:"+password);
8 //response.setContentType("text/html");
9 PrintWriter out = response.getWriter();
10 if(us.login(username, password))
11 {
12 //用户登录成功!
13 out.println("success");
14 }
15 else //用户登录失败
16 out.println("failed");
17 out.flush();
18 out.close();
19 } </span>
<span style="font-size:16px;">1 public void doPost(HttpServletRequest request, HttpServletResponse response)
2 throws ServletException, IOException {
3 UserService us = UserService.getInstance();
4 String username = request.getParameter("username"); //获得从客户端传入的用户名和密码
5 String password = request.getParameter("password");
6 //System.out.println("username:"+username);
7 //System.out.println("password:"+password);
8 //response.setContentType("text/html");
9 PrintWriter out = response.getWriter();
10 if(us.login(username, password))
11 {
12 //用户登录成功!
13 out.println("success");
14 }
15 else //用户登录失败
16 out.println("failed");
17 out.flush();
18 out.close();
19 } </span>
2.客户端,首先创建一个登录Activity。如图所示:
当用户点击登录按钮后,创建一个http请求,发送到服务器端。获得服务器返回的结果后,再进行判断并执行相关操作。
httpclient相当于一个浏览器,通过它,可以很方便的发出GET,POST请求。
该Activity的具体代码如下:
[java] <span style="font-size:16px;">20 public class GossipActivity extends Activity {
21 /** Called when the activity is first created. */
22
23 pivate EditText usernameEdit;
24 private EditText passwordEdit;
25 private Button loginButton;
26
27 @Override
28 public void onCreate(Bundle savedInstanceState) {
29 super.onCreate(savedInstanceState);
30 setContentView(R.layout.main);
31
32 usernameEdit = (EditText)findViewById(R.id.usernameEdit);
33 passwordEdit = (EditText)findViewById(R.id.pwdEdit);
34 loginButton = (Button)findViewById(R.id.loginButton);
35
36 loginButton.setOnClickListener(loginListener);
37 }
38
39 //登陆监听器
40 OnClickListener loginListener = new OnClickListener(){
41
42 @Override
43 public void onClick(View v) {
44 System.out.println("Login Button clicked!");
45 String httpUrl = "http://10.0.2.2:8089/Gossip/LoginServlet";
46 System.out.println(httpUrl);
47 HttpPost request = new HttpPost(httpUrl);
48 HttpClient httpClient = new DefaultHttpClient();
49 //传递参数
50 List<NameValuePair> params = new ArrayList<NameValuePair>();
51 params.add(new BasicNameValuePair("username",usernameEdit.getText().toString()));
52 params.add(new BasicNameValuePair("password",passwordEdit.getText().toString()));
53 HttpResponse response;
54 try {
55 HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
56 request.setEntity(entity);
57 response = httpClient.execute(request);
58
59 //如果返回状态为200,获得返回的结果
60 if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
61 String str = EntityUtils.toString(response.getEntity());
62 System.out.println("response:"+str);
63 if(str.trim().equals("success")){
64 //用户登录成功
65 System.out.println("登录成功!");
66 Intent intent = new Intent(GossipActivity.this,GossiplistActivity.class);
67 startActivity(intent);
68 }
69 else{
70 //用户登录失败
71 System.out.println("登录失败!");
72 }
73 }else{
74 System.out.println("连接失败!");
75 }
76 } catch (ClientProtocolException e) {
77 // TODO Auto-generated catch block
78 e.printStackTrace();
79 } catch (IOException e) {
80 // TODO Auto-generated catch block
81 e.printStackTrace();
82 }
83
84 }};
85 } </span>
<span style="font-size:16px;">20 public class GossipActivity extends Activity {
21 /** Called when the activity is first created. */
22
23 private EditText usernameEdit;
24 private EditText passwordEdit;
25 private Button loginButton;
26
27 @Override
28 public void onCreate(Bundle savedInstanceState) {
29 super.onCreate(savedInstanceState);
30 setContentView(R.layout.main);
31
32 usernameEdit = (EditText)findViewById(R.id.usernameEdit);
33 passwordEdit = (EditText)findViewById(R.id.pwdEdit);
34 loginButton = (Button)findViewById(R.id.loginButton);
35
36 loginButton.setOnClickListener(loginListener);
37 }
38
39 //登陆监听器
40 OnClickListener loginListener = new OnClickListener(){
41
42 @Override
43 public void onClick(View v) {
44 System.out.println("Login Button clicked!");
45 String httpUrl = "http://10.0.2.2:8089/Gossip/LoginServlet";
46 System.out.println(httpUrl);
47 HttpPost request = new HttpPost(httpUrl);
48 HttpClient httpClient = new DefaultHttpClient();
49 //传递参数
50 List<NameValuePair> params = new ArrayList<NameValuePair>();
51 params.add(new BasicNameValuePair("username",usernameEdit.getText().toString()));
52 params.add(new BasicNameValuePair("password",passwordEdit.getText().toString()));
53 HttpResponse response;
54 try {
55 HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
56 request.setEntity(entity);
57 response = httpClient.execute(request);
58
59 //如果返回状态为200,获得返回的结果
60 if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
61 String str = EntityUtils.toString(response.getEntity());
62 System.out.println("response:"+str);
63 if(str.trim().equals("success")){
64 //用户登录成功
65 System.out.println("登录成功!");
66 Intent intent = new Intent(GossipActivity.this,GossiplistActivity.class);
67 startActivity(intent);
68 }
69 else{
70 //用户登录失败
71 System.out.println("登录失败!");
72 }
73 }else{
74 System.out.println("连接失败!");
75 }
76 } catch (ClientProtocolException e) {
77 // TODO Auto-generated catch block
78 e.printStackTrace();
79 } catch (IOException e) {
80 // TODO Auto-generated catch block
81 e.printStackTrace();
82 }
83
84 }};
85 } </span>
在数据库中添加一行:用户名为123,密码为456。登录后调转到另一Activity并在控制台中打印调试信息,结果如下:
3 在向本机发送HTTP请求时,有一点必须注意,就是在android 虚拟机中,127.0.0.1为android 虚拟机的IP地址,
如果要访问本机,IP地址应该改为10.0.2.2。否则肯定会导致访问不成功!
作者:余蒙