SpringMVC利用原生servlet实现与安卓端数据交互

服务器端

/*安卓新增用户*/
	@RequestMapping(value="/addUserA",method = RequestMethod.POST)
	public void addUserA(HttpServletResponse response,HttpServletRequest request) throws Exception {
		
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		
		user.setUserName(userName);
		user.setPassword(password);
		if(savedata(user)) {
			response.getOutputStream().write(("yes").getBytes("utf-8"));
		}else {
			response.getOutputStream().write(("no").getBytes("utf-8"));
		}
	}

/*android验证用户*/
	@RequestMapping(value="/validateUserA.do",method = RequestMethod.POST)
	@ResponseBody
	public void login_android(
			HttpServletResponse response,HttpServletRequest request) throws UnsupportedEncodingException, IOException {
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		int i;
		try {
			user.setUserName(userName);
			user.setPassword(password);
			i = search(userName,password);
			System.out.println(userName + " " + password);
			if(i == 1) {
				response.getOutputStream().write(("yes").getBytes("utf-8"));
			}else if(i == 0){
				response.getOutputStream().write(("no").getBytes("utf-8"));
			}else {
				response.getOutputStream().write(("nop").getBytes("utf-8"));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

其余代码看我上两篇博客SpringMVC 实现登录注册-1SpringMVC 实现登录注册-2

 

安卓端

布局文件就不贴出来了,就是两个EditText和一个Button

LoginActivity.java
//登录
    private void Login(){
        mUserSignInButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(LoginActivity.this, "正在提交请求", Toast.LENGTH_SHORT).show();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String username = mUsernameView.getText().toString();
                        String password = mPasswordView.getText().toString();
                        //final String response = LoginService.loginByGet(username,password);
                        final String response = LoginService.loginByPost(username,password);
                        if(response != ""){
                            showResponse(response);
                        }else{
                            showResponse("请求失败....!");
                        }

                    }
                }).start();
            }
        });
    }

    //显示返回数据
    private void showResponse(final String response){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(response.equals("yes")){
                    Toast.makeText(LoginActivity.this, "登录成功!", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(LoginActivity.this,MainActivity.class);
                    startActivity(intent);
                }
                else if(response.equals("no"))
                    Toast.makeText(LoginActivity.this, "无此账号", Toast.LENGTH_SHORT).show();
                else if(response.equals("nop"))
                    Toast.makeText(LoginActivity.this, "密码错误", Toast.LENGTH_SHORT).show();
                else
                    Toast.makeText(LoginActivity.this, response, Toast.LENGTH_SHORT).show();
            }
        });
    }
LoginService.java
public static String loginByGet(String username,String  password){
        try {
            String path = ServletUrl.BASE_URL+ServletUrl.LOGIN_URL+"?userName="
                    + URLEncoder.encode(username,"UTF-8") + "&password=" + URLEncoder.encode(password,"UTF-8");
            URL url = new URL(path);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET"); //设置请求方式为get
            connection.setConnectTimeout(5000); //设置连接超时间为5秒
            int code = connection.getResponseCode(); //获得请求码
            if(code == 200){
                InputStream inputStream = connection.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
                String s = br.readLine();
                return s;
            }else{
                return null;
            }

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("出错了!");
        }
        return null;
    }

    public static String loginByPost(String username,String  password){
        try {
            //要访问的资源路径
            //资源路径类似"http://193.168.3.16:8080/Login/login";
            //IP地址/你的web项目名/接口名称
            //IP地址是内网地址,不能直接使用,web与Android在同一个网络即可使用,即连热点,我这                    
              里是采用花生壳来实现内网穿透
            String path = ServletUrl.BASE_URL+ServletUrl.LOGIN_URL;
            //创建URL的实例
            URL url = new URL(path);
            //获取HttpURLConnection对象
            HttpURLConnection conn =  (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            //设置超时时间
            conn.setReadTimeout(5000);
            //指定请求方式
            conn.setRequestMethod("POST");
            //准备数据,将参数编码
            String data = "userName="+URLEncoder.encode(username)+"&password="
                    +URLEncoder.encode(password);
            System.out.println(data);
            //设置请求头
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Content-length",data.length()+"");
            //将数据写给服务器
            conn.setDoOutput(true);
            //得到输出流
            OutputStream os = conn.getOutputStream();
            os.write(data.getBytes()); //将数据写入输出流中
            int code = conn.getResponseCode(); //获取服务器返回的状态码
            if(code == 200){
                //得到服务器返回的输入流
                InputStream inputStream = conn.getInputStream();
                //将输入流换成字符串
                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
                String s = br.readLine();
                return s;
            }else
                return null;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("出错了!");
        }
        return null;
    }
注册部分的代码就不贴出来了,跟登录的代码一样,就是接口名称换一下就可以了!

Android端要在清单文件里添加网络权限

<uses-permission android:name="android.permission.INTERNET" />

 

每天进步一点点!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值