Android客户端+JavaWeb服务器远程登入

一、Android客户端

 1、登入界面main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  android:gravity="center"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:textSize="20sp"
    android:text="用户登陆"/>
<LinearLayout android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
>
	<TextView  android:gravity="right"
    android:layout_width="100dp" 
    android:layout_height="wrap_content" 
    android:text="用户名:"/>
	<EditText  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:id="@+id/username"/>
</LinearLayout>
<LinearLayout android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
>
	<TextView  android:gravity="right"
    android:layout_width="100dp" 
    android:layout_height="wrap_content" 
    android:text="密码:"/>
    <EditText  android:password="true"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:id="@+id/password"/>
</LinearLayout>
<LinearLayout android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
>
	<Button  android:layout_marginLeft="160px"
	android:id="@+id/login"
    android:layout_width="100dp" 
    android:layout_height="wrap_content" 
    android:text="登陆"/>
    <Button  android:id="@+id/reset"
    android:layout_width="100dp" 
    android:layout_height="wrap_content" 
    android:text="重置"/>
</LinearLayout>


</LinearLayout>

2、LoginActivity

package com.bao;

import android.app.Activity;
import android.os.Bundle;
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 {
    /** Called when the activity is first created. */
	
	private EditText username;
	private EditText password;
	private Button login;
	private Button reset;
	UserManager userManager;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        username = (EditText)findViewById(R.id.username);
        password = (EditText)findViewById(R.id.password);
        login = (Button)findViewById(R.id.login);
        reset = (Button)findViewById(R.id.reset);
        userManager = new UserManager();
        login.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				boolean isSuccess = userManager.isRightUser(username.getText().toString(), password.getText().toString());
				if(isSuccess == true){
					Toast.makeText(LoginActivity.this, "登陆成功", Toast.LENGTH_LONG).show();
				}else{
					Toast.makeText(LoginActivity.this, "密码或用户名错误", Toast.LENGTH_LONG).show();
					
				}
			}
		});
        
        reset.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				username.setText("");
				password.setText("");
			}
		});
    
    }
}

3、用户管理类UserManager

package com.bao;

public class UserManager {
	UrlConnectionToServer urlConnectionToServer = new UrlConnectionToServer();
	
	HttpClientToServer httpClientToServer = new HttpClientToServer();
	
	public boolean isRightUser(String username,String password){
		
		//使用urlConnection POST连接服务器
		//String response = urlConnectionToServer.doPost(username, password);
		
		//使用urlConnection Get连接服务器
		//String response = urlConnectionToServer.doGet(username, password);
		
		//使用HttpClientGet连接服务器
		//String response = httpClientToServer.doGet(username, password);
		
		//使用HttpClientPOST连接服务器
		String response = httpClientToServer.doPost(username, password);
		if("true".equals(response)){
			return true;
		}else{
			return false;
		}
		
		
	}

}

4、连接服务器httpClientToServer

package com.bao;

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;
import org.apache.http.util.EntityUtils;

public class HttpClientToServer {
	
	String urlAddress = "http://10.0.0.10:8080/AndroidServer/login.do";
	public HttpClientToServer(){
			
		}
		
	public String doGet(String username,String password){
		
		String getUrl = urlAddress + "?username="+username+"&password="+password;
		HttpGet httpGet = new HttpGet(getUrl);
		//HttpParams hp = httpGet.getParams();
		//hp.
		//httpGet.setp
		HttpClient hc = new DefaultHttpClient();
		try {
			HttpResponse ht = hc.execute(httpGet);
			if(ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
				HttpEntity he = ht.getEntity();
				InputStream is = he.getContent();
				BufferedReader br = new BufferedReader(new InputStreamReader(is));
				String response = "";
				String readLine = null;
				while((readLine =br.readLine()) != null){
					//response = br.readLine();
					response = response + readLine;
				}
				is.close();
				br.close();
				
				//String str = EntityUtils.toString(he);
				System.out.println("========="+response);
				return response;
			}else{
				return "error";
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "exception";
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "exception";
		}
		
		
		
		
	}
	
	public String doPost(String username,String password){
		//String getUrl = urlAddress + "?username="+username+"&password="+password;
		HttpPost httpPost = new HttpPost(urlAddress);
		List params = new ArrayList();
		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) {
			// TODO Auto-generated catch block
			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 = br.readLine();
					response = response + readLine;
				}
				is.close();
				br.close();
				
				//String str = EntityUtils.toString(he);
				System.out.println("========="+response);
				return response;
			}else{
				return "error";
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "exception";
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "exception";
		}
		
	}

}

5、使用urlConnection POST连接服务器

package com.bao;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class UrlConnectionToServer {
	
	String urlAddress = "http://10.0.0.10:8080/AndroidServer/login.do";
	URL url;
	HttpURLConnection uRLConnection;
	public UrlConnectionToServer(){
		
	}
	
	public String doGet(String username,String password){
		
		String getUrl = urlAddress + "?username="+username+"&password="+password;
		try {
			url = new URL(getUrl);
			uRLConnection = (HttpURLConnection)url.openConnection();
			InputStream is = uRLConnection.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			String response = "";
			String readLine = null;
			while((readLine =br.readLine()) != null){
				//response = br.readLine();
				response = response + readLine;
			}
			is.close();
			br.close();
			uRLConnection.disconnect();
			return response;
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		
	}
	
	public String doPost(String username,String password){
		try {
			url = new URL(urlAddress);
			uRLConnection = (HttpURLConnection)url.openConnection();
			uRLConnection.setDoInput(true);
			uRLConnection.setDoOutput(true);
			uRLConnection.setRequestMethod("POST");
			uRLConnection.setUseCaches(false);
			uRLConnection.setInstanceFollowRedirects(false);
			uRLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			uRLConnection.connect();
			
			DataOutputStream out = new DataOutputStream(uRLConnection.getOutputStream());
			String content = "username="+username+"&password="+password;
			out.writeBytes(content);
			out.flush();
			out.close();
			
			InputStream is = uRLConnection.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			String response = "";
			String readLine = null;
			while((readLine =br.readLine()) != null){
				//response = br.readLine();
				response = response + readLine;
			}
			is.close();
			br.close();
			uRLConnection.disconnect();
			return response;
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		
	}

}

二、服务器

  2.1、界面

<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>

  <body>
    	登陆测试. <hr>
    	<form action="login.do" method="post">
    		<input type="text" name="username"/><br/>
    		<input type="password" name="password"/><br/>
    		<input type="submit" value="submit"/>
    		<input type="reset" value="reset"/>
    	</form>
  </body>
</html>

2.1、servlet处理模块LoginServlet

package com.bao;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * 登陆servlet
 * @author Fly
 * @Email jianbao_216@163.com
 *
 */
public class LoginServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		//super.doGet(req, resp);
		System.out.println("=========doGet========");
		this.doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		//super.doPost(req, resp);
		PrintWriter pw = resp.getWriter();
		System.out.println("=========doPost========");
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		System.out.println("=========username========"+username);
		System.out.println("=========password========"+password);
		
		//实际为数据库查询,模拟登陆成功
		if("test".equals(username) && "test".equals(password)){
			pw.println(true);
		}else{
			pw.println(false);
		}
	}
	
	

}




  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值