java与安卓接口_安卓实现与接口交互

前言

app端作为用户使用端,对于实现许多后端功能并不方便。通过访问接口实现前后端的交互既能提高开发的效率,也方便了功能的及时修改。

接口端

将前端需要的大部分功能进行实现,并提供一个url供前端进行访问,本文采用的是javaee+tomcat

[0] 建立一个javaweb项目

[1] 编写bean层实现数据类的封装 这里以建立一个user类为范例,提供了get方法获取user的个人账户信息

package bean;

public class User {

private String uname;

private String passwd;

public User(String uname,String passwd) {

this.uname = uname;

this.passwd =passwd;

}

public User()

{

}

public String getName()

{

return uname;

}

public String getPwd()

{

return passwd;

}

}

[2] 编写Dao层实现对数据库的访问与修改 对于数据库的操作统一由dao层进行封装,再由其他层进行调用 这里编写了一个userDao,提供一个checkuser方法进行用户的登录验证,需要安装jdbc对数据库进行访问,这里采用的是mysql的jdbc

package dao;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import com.mysql.jdbc.*;

import bean.User;

public class userDao {

public boolean checkUser(User u)

{

boolean flag = false;

String name = u.getName();

String psw = u.getPwd();

//String url = "jdbc:mysql://123.206.128.233:3306/smart_medical"; try {

Class.forName("com.mysql.jdbc.Driver");

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block e.printStackTrace();

}

Connection con = null;

try {

con = DriverManager.getConnection("jdbc:mysql://123.206.128.233:3306/smart_medical?user=root&password=");

} catch (SQLException e) {

// TODO Auto-generated catch block e.printStackTrace();

}

Statement statement = null;

try {

statement = con.createStatement();

} catch (SQLException e) {

// TODO Auto-generated catch block e.printStackTrace();

}

try {

ResultSet re = statement.executeQuery("select * from Doctor");

while(re.next())

{

if(name.equals(re.getString("username"))&&psw.equals(re.getString("pwd")))

{

statement.close();

con.close();

return true;

}

}

} catch (SQLException e) {

// TODO Auto-generated catch block e.printStackTrace();

}

try {

statement.close();

} catch (SQLException e) {

// TODO Auto-generated catch block e.printStackTrace();

}

try {

con.close();

} catch (SQLException e) {

// TODO Auto-generated catch block e.printStackTrace();

}

return false;

}

}

[3] 编写servlet层实现数据库的调用和与前端数据的传递与交互 这里编写了一个用于登录验证的servlet,通过request获取前端发送的信息,调用userDao中的checkUser方法进行用户验证并获得结果,并将结果转换成json格式打印返回给前端用于反馈登录是否成功以及更多信息。

package servlet;

import java.io.IOException;

import java.io.PrintWriter;

import java.util.HashMap;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

import com.google.gson.Gson;

import bean.Login_result;

import bean.User;

import dao.userDao;

/*** Servlet implementation class Login_servlet*/

@WebServlet("/Login_servlet")

public class Login_servlet extends HttpServlet {

private static final long serialVersionUID = 1L;

/*** @see HttpServlet#HttpServlet()*/

public Login_servlet() {

super();

// TODO Auto-generated constructor stub }

/*** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)*/

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setHeader("Access-Control-Allow-Origin", "*");//跨域访问 request.setCharacterEncoding("UTF-8");

response.setCharacterEncoding("UTF-8");

HttpSession session = request.getSession();

String uname = request.getParameter("account");

String passwd = request.getParameter("password");

Login_result re;

User u = new User(uname,passwd);

userDao udao = new userDao();

if(udao.checkUser(u))

{

re = new Login_result("success", true,uname,passwd);

Gson gson = new Gson();

String json = gson.toJson(re);

session.setAttribute("rs", json);

PrintWriter pw = response.getWriter();

pw.print(json);

pw.flush();

pw.close();

}

else {

re = new Login_result("failed", false, null,null);

Gson gson = new Gson();

String json = gson.toJson(re);

session.setAttribute("rs", json);

PrintWriter pw = response.getWriter();

pw.print(json);

pw.flush();

pw.close();

}

}

/*** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)*/

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

// TODO Auto-generated method stub doGet(request, response);

}

}

[3]部署 通过将项目部署到服务器供安卓端访问。服务器端安装好tomcat后,将项目导出成war文件,将项目文件放入webapp目录中。 部署成功后可通过ip:tomcat端口号/项目名访问项目。

Android端

安卓对于耗时访问请求,为了防止访问阻塞,使得主线程进入假死状态,安卓端访问接口需要通过子线程进行访问。 对于UI的修改,为了安全性,不可通过子线程修改,所以需要使用消息传递机制,将子线程访问获取的数据发送给主线程,通过主线程实现UI的修改。 这里实现了一个登录验证,子线程通过post请求发送用户名与密码,接口端返回登录结果。通过消息传递发送给主线程,主线程获取消息后实现登录跳转

package com.example.a61721.smartapp;

import android.app.Activity;

import android.content.Intent;

import android.os.Bundle;

import android.os.Handler;

import android.os.Message;

import android.util.Log;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import com.google.gson.Gson;

import java.io.ByteArrayOutputStream;

import java.io.InputStream;

import java.io.PrintWriter;

import java.net.HttpURLConnection;

import java.net.URL;

import java.net.URLEncoder;

import java.util.HashMap;

import bean.Login_result;

public class LoginActivity extends Activity {

String TAG = LoginActivity.class.getCanonicalName();

private EditText account;

private EditText password;

private boolean passport = false;

private HashMap StringMap;

private Handler loginHandler = new Handler()

{

public void handleMessage(Message msg)

{

if(msg.getData().getBoolean("result")==true)

passport = true;

else

passport = false;

if(passport==true) {

Intent i = new Intent(LoginActivity.this, MenuActivity.class);

startActivity(i);

}

}

};

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_login);

account = findViewById(R.id.account);

password = findViewById(R.id.password);

StringMap = new HashMap<>();

Button b_login = findViewById(R.id.button_login);

b_login.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

StringMap.put("account",account.getText().toString());

StringMap.put("password",password.getText().toString());

new Thread(postRun).start();

}

});

}

Runnable postRun = new Runnable() {

@Override

public void run() {

requestPost(StringMap);

}

};

private void requestPost(HashMap paramsMap) {

try {

String baseUrl = "http://123.206.128.233:8080/Smart_Medical/servlet/Login_servlet";

//合成参数 StringBuilder tempParams = new StringBuilder();

int pos = 0;

for (String key : paramsMap.keySet()) {

if (pos >0) {

tempParams.append("&");

}

tempParams.append(String.format("%s=%s", key, URLEncoder.encode(paramsMap.get(key), "utf-8")));

pos++;

}

String params = tempParams.toString();

Log.e(TAG,"params--post-->>"+params);

// 请求的参数转换为byte数组// byte[] postData = params.getBytes(); // 新建一个URL对象 URL url = new URL(baseUrl);

// 打开一个HttpURLConnection连接 HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();

// 设置连接超时时间 urlConn.setConnectTimeout(5 * 1000);

//设置从主机读取数据超时 urlConn.setReadTimeout(5 * 1000);

// Post请求必须设置允许输出 默认false urlConn.setDoOutput(true);

//设置请求允许输入 默认是true urlConn.setDoInput(true);

// Post请求不能使用缓存 urlConn.setUseCaches(false);

// 设置为Post请求 urlConn.setRequestMethod("POST");

//设置本次连接是否自动处理重定向 urlConn.setInstanceFollowRedirects(true);

// 开始连接 urlConn.connect();

// 发送请求参数 PrintWriter dos = new PrintWriter(urlConn.getOutputStream());

dos.write(params);

dos.flush();

dos.close();

// 判断请求是否成功 if (urlConn.getResponseCode() == 200) {

// 获取返回的数据 String result = streamToString(urlConn.getInputStream());

Gson gson = new Gson();

Login_result user = gson.fromJson(result, Login_result.class);

Log.e(TAG,""+user.result);

Message msg = new Message();

Bundle bundle = new Bundle();

bundle.putBoolean("result",user.result);

msg.setData(bundle);

loginHandler.sendMessage(msg);

} else {

}

// 关闭连接 urlConn.disconnect();

} catch (Exception e) {

Log.e(TAG, e.toString());

}

}

/*** 将输入流转换成字符串** @param is 从网络获取的输入流* @return*/

public String streamToString(InputStream is) {

try {

ByteArrayOutputStream baos = new ByteArrayOutputStream();

byte[] buffer = new byte[1024];

int len = 0;

while ((len = is.read(buffer)) != -1) {

baos.write(buffer, 0, len);

}

baos.close();

is.close();

byte[] byteArray = baos.toByteArray();

return new String(byteArray);

} catch (Exception e) {

Log.e(TAG, e.toString());

return null;

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值