android学习笔记(3)与SSH后台交互

  • Post author:
  • Post category:其他


实现的目标是android登录SSH后台的一个,

具体实现为需要 与SSH后台连接的代码为:

package com.example.util;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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 HttpUtil {


	// 创建HttpClient对象
	public static HttpClient httpClient = new DefaultHttpClient();
	public static final String BASE_URL =
		"http://218.194.144.72:8080/RegisteMG/";
	/**
	 *
	 * @param url 发送请求的URL
	 * @return 服务器响应字符串
	 * @throws Exception
	 */
	public static String getRequest(final String url)
		throws Exception
	{
		FutureTask<String> task = new FutureTask<String>(
		new Callable<String>()
		{
			@Override
			public String call() throws Exception
			{
				// 创建HttpGet对象。
				HttpGet get = new HttpGet(url);
				// 发送GET请求
				HttpResponse httpResponse = httpClient.execute(get);
				// 如果服务器成功地返回响应
				if (httpResponse.getStatusLine()
					.getStatusCode() == 200)
				{
					// 获取服务器响应字符串
					String result = EntityUtils
						.toString(httpResponse.getEntity());
					return result;
				}
				return null;
			}
		});
		new Thread(task).start();
		return task.get();
	}

	/**
	 * @param url 发送请求的URL
	 * @param params 请求参数
	 * @return 服务器响应字符串
	 * @throws Exception
	 */
	public static String postRequest(final String url
		, final Map<String ,String> rawParams)throws Exception
	{
		FutureTask<String> task = new FutureTask<String>(
		new Callable<String>()
		{
			@Override
			public String call() throws Exception
			{
				// 创建HttpPost对象。
				HttpPost post = new HttpPost(url);
				// 如果传递参数个数比较多的话可以对传递的参数进行封装
				List<NameValuePair> params = 
					new ArrayList<NameValuePair>();
				for(String key : rawParams.keySet())
				{
					//封装请求参数
					params.add(new BasicNameValuePair(key 
						, rawParams.get(key)));
				}
				// 设置请求参数
				post.setEntity(new UrlEncodedFormEntity(
					params, "UTF-8"));
				// 发送POST请求
				HttpResponse httpResponse = httpClient.execute(post);
				// 如果服务器成功地返回响应
				if (httpResponse.getStatusLine()
					.getStatusCode() == 200)
				{
					// 获取服务器响应字符串
					String result = EntityUtils
						.toString(httpResponse.getEntity());
					return result;
				}
				return null;
			}
		});
		new Thread(task).start();
		return task.get();
	}
}

登录的代码为:

package com.example.registemg_mobel;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;


/*import com.example.shenwu.MainActivity;*/
import com.example.util.HttpUtil;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class Login extends Activity {
	EditText etName,etPass;
	Button bnLogin,bnCancel;
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_main);
	etName=(EditText) findViewById(R.id.userEditText);
	etPass=(EditText) findViewById(R.id.pwdEditText);
	bnLogin=(Button) findViewById(R.id.bnLogin);
	bnCancel=(Button) findViewById(R.id.bnCancel);
	/*bnCancel.setOnClickListener(new HomeListener(this));*///重置按钮
	bnCancel.setOnClickListener(new OnClickListener(){

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			finish();
		}
		
	});
	bnLogin.setOnClickListener(new OnClickListener(){

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if(validate())
			{
				if(loginpro())
				{
					Log.v("jsonobj", "************已经登录成功了!!**********************");  
					Intent intent=new Intent(Login.this,ac.class);
					intent.putExtra("abc", "abcd");
					startActivity(intent);
					finish();
				}
				else
				{
					new AlertDialog.Builder(Login.this).setMessage("用户名或密码错误").setPositiveButton("确定",null).show();
				}
			}
			
		}
		
	});
	
	}
	public boolean loginpro()
	{
		String username=etName.getText().toString();
		String pwd=etPass.getText().toString();
		JSONObject jsonobj;
		try
		{
			jsonobj=query(username,pwd);
			Log.v("jsonobj", jsonobj+"**************************************");  
			if(jsonobj.getInt("userId")>0)
			{
				return true;
			}
			else
			{
				return false;
			}
			
					
			
		}catch(Exception e)
		{
			new AlertDialog.Builder(Login.this).setMessage("服务器异常!"+e.getMessage()).setPositiveButton("确定",null).show();
		}
		return false;
	}
	public boolean validate()
	{
		String username =etName.getText().toString();
		if(username.equals(""))
		{
			new AlertDialog.Builder(Login.this).setMessage("帐号不能为空!").setPositiveButton("确定",null).show();
			return false;
		}
		String pwd=etPass.getText().toString();
		if(pwd.equals(""))
		{
			new AlertDialog.Builder(Login.this).setMessage("密码不能为空!").setPositiveButton("确定",null).show();
			return false;
		}
		return true;
	}
	public JSONObject query(String username,String password) throws Exception
	{
		Map<String,String> map=new HashMap<String,String>();
		map.put("user", username);
		map.put("pass", password);
		String uri=HttpUtil.BASE_URL+"android.action";
		Log.v("url", uri+"**************************************"); 
		return new JSONObject(HttpUtil.postRequest(uri, map));
		
		
		
	}
	 /*@Override
	    protected void onDestroy(){
	        super.onDestroy();
	        unbindService(serviceconnection);
	    }*/

}

SSH后台接收数据

package com.MG.action;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.struts2.json.annotations.JSON;

import com.MG.entity.User;
import com.MG.service.UserService;
import com.opensymphony.xwork2.ActionSupport;

public class AndroidAction extends ActionSupport
{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	 UserService userService;
	
	
	 @JSON(serialize = false)
	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	String user;
	public void setUser(String user) {
		this.user = user;
	}

	public void setPass(String pass) {
		this.pass = pass;
	}

	String pass;
	Map aa;
	
	public Map getAa() {
		return aa;
	}

	public void setAa(Map aa) {
		this.aa = aa;
	}

	public String  execute()
	{
		Map<String,Object> map=new HashMap<String,Object>();
		String password=this.pass;
		String username=this.user;
		String aa="111";
		int userId=0;
		
		System.out.println(aa);
		System.out.println(username);
		System.out.println(password);
		
		System.out.println(map);
		
		List<User> users = userService.findAlllogin();
		Iterator<User> user = users.iterator();
		
		//重新生成MD5 与数据库的MD5 校验
		StringBuffer buf = new StringBuffer(""); 
		try { 
			MessageDigest md = MessageDigest.getInstance("MD5"); 
			md.update(password.getBytes()); 
			byte b[] = md.digest(); 

			int i; 

			
			for (int offset = 0; offset < b.length; offset++) { 
			i = b[offset]; 
			if(i<0) i+= 256; 
			if(i<16) 
			buf.append("0"); 
			buf.append(Integer.toHexString(i)); 
			} 			

			} catch (NoSuchAlgorithmException e) { 
			// TODO Auto-generated catch block 
			e.printStackTrace(); 
			} 
		
		
		
		
		while (user.hasNext()) {
			User u = user.next();
			if ((u.getStuname().trim().equals(username))
					&& (u.getStupassword().trim().equals(buf.toString()))) {

				
				System.out.println("登陆成功");
				userId=2;
				map.put("userId", userId);
				this.setAa(map);
				return  SUCCESS;
			} else
				continue;
		}
		userId=-1;
		map.put("userId", userId);
		this.setAa(map);
		return SUCCESS ;
	
	}
}


		
		
		
		
		
/*	}
	
	
}*/

/*public class AndroidAction extends BaseServlet {

	*//**
	 * 
	 *//*
	private static final long serialVersionUID = 1L;
	
	 public void service(HttpServletRequest request ,
				HttpServletResponse response)
				throws IOException , ServletException
			{
				String user = request.getParameter("user");
				String pass = request.getParameter("pass");
				int userId=123;
				// 获取系统的业务逻辑组件
				AuctionManager auctionManager = (AuctionManager)getCtx().getBean("mgr");
				// 验证用户登录
				int userId = auctionManager.validLogin(user , pass);
				response.setContentType("text/html; charset=GBK");
				// 登录成功
				if (userId > 0)
				{
				System.out.println(user);
				System.out.println("111111111");
				System.out.println(pass);
				System.out.println("111111111");
					request.getSession(true).setAttribute("userId" , 2222);
				}
				try
				{
					// 把验证的userId封装成JSONObject
					JSONObject jsonObj = (JSONObject) new JSONObject().put("userId" , userId);
					// 输出响应
					response.getWriter().println(jsonObj.toString());
				}
				catch (JSONException ex)
				{
					ex.printStackTrace();
				}
			}
	

	
}*/



版权声明:本文为a550246215原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。