前言
在上文Android入门案例(二)——JDBC连接MySql数据库实现登录中我们已经实现JDBC直连数据库,我在结尾也说过实际开发中一般是Android端访问web后台,由后台程序接受参数去访问数据库,并返回访问结果给Android端,本文我们来实现HTTP方式的登录小案例。
在项目中实现注册登录有很多种方式,一般对于初学者来说,不使用框架,采用http的post和get请求后台服务器,是一种更好理解底层源码的方式。使用框架实现注册登录虽然比自己封装post和get请求后台方便,但是不利于我们更好地理解其中的原理和机制。
一、准备
1.服务器端设计
我这里用eclipse实现了一个很简单的web项目
- 新建Web Project,命名为Android
- 采用servlet编程,所以不需要任何jsp页面。
- 导包:
,
自行下载
其中,User.java在Android入门案例(一)——简单登录中可以找到
DBUtils.java在Android入门案例(二)——JDBC连接MySql数据库实现登录可以找到
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
// 接收客户端信息
User user = new User(request.getParameter("username"),request.getParameter("password"));
// 验证处理
System.out.println("Android端接收数据成功!!!"+user);
Map<String, String> map = DBUtils.login(user);
PrintWriter out = null;
if(map!=null) {
System.out.println("数据查询成功!!!");
// 返回信息到客户端
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
out = response.getWriter();
out.write("success"); //一般返回json数据,这里从简
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
Tomact启动web项目成功!
2.Android端设计
在http://mirrors.hust.edu.cn/apache//httpcomponents/httpclient/binary/httpcomponents-client-4.5.5-bin.zip中下载资 源,解压后将上图中http的jar包复制到Android项目中的libs中并右键Add as libs,导入时应该会编译报错,可参考jar包导入冲突
- 导入http相关的jar包
User.java、infoActivity.java、activity_info.xml、activity_main.xml在Android入门案例(一)——简单登录中都有
二、建立连接
public class Main2Activity extends AppCompatActivity implements View.OnClickListener {
Button login, cancle;
EditText user, pwd;
RadioButton man, woman;
String username, password, sex;
User u;
private String url = "http://10.0.2.2:8080/Android/LoginServlet";//服务器接口地址
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
login = (Button) findViewById(R.id.btn_login);
cancle = (Button) findViewById(R.id.btn_cancel);
user = (EditText) findViewById(R.id.et_username);
pwd = (EditText) findViewById(R.id.et_password);
man = (RadioButton) findViewById(R.id.rb_man);
woman = (RadioButton) findViewById(R.id.rb_woman);
login.setOnClickListener(this);
cancle.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_login:
/**
* 开辟一个子线程访问网络,否则会抛出异常
*/
new Thread() {
@Override
public void run() {
username = user.getText().toString().trim();
password = pwd.getText().toString().trim();
if(man.isClickable()) {
sex = "男";
} else if(woman.isClickable()) {
sex = "女";
}
u = new User(username,password,sex);
NameValuePair pair1 = new BasicNameValuePair("username", username);
NameValuePair pair2 = new BasicNameValuePair("password", password);
List<NameValuePair> pairList = new ArrayList<NameValuePair>();
pairList.add(pair1);
pairList.add(pair2);
try {
HttpEntity requestHttpEntity = new UrlEncodedFormEntity(pairList);
// URl是接口地址
HttpPost httpPost = new HttpPost(url);
// 将请求体内容加入请求中
httpPost.setEntity(requestHttpEntity);
// 需要客户端对象来发送请求
HttpClient httpClient = new DefaultHttpClient();
// 发送请求
HttpResponse response = httpClient.execute(httpPost);
// 显示响应
if(getInfo(response)) {
Intent intent=new Intent(Main2Activity.this,infoActivity.class);
intent.putExtra("user",u);
startActivity(intent);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
break;
}
}
// 收取数据
private static boolean getInfo(HttpResponse response) throws Exception {
HttpEntity httpEntity = response.getEntity();
InputStream inputStream = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String result = "";
String line = "";
while (null != (line = reader.readLine())){
result += line;
}
if(result.equals("success")) {
return true;
}
return false;
}
}
启动安卓项目,登录成功!
web后台输出数据!