Android请求获取Java后端数据的例子
主要实现:
java后端的代码 + Android的代码
(1)、先创个User类
package com.szerp.android.entity;
import net.sf.json.JSONObject;
public class User {
private String userid;
private String account;
private String username;
private String passwd;
public User() {
}
public User(String userid, String account, String username, String passwd) {
this.userid = userid;
this.account = account;
this.username = username;
this.passwd = passwd;
}
public static User json2novel (JSONObject json) {
try {
return new User(json.getString("userid"),
json.getString("account"),
json.getString("username"),
json.getString("passwd")
);
}catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
}
(2)、建个LoginServlet(public class LoginServlet extends HttpServlet)
package com.szerp.android.service.impl;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jeecgframework.core.util.PasswordUtil;
import org.jeecgframework.web.system.pojo.base.TSBaseUser;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import com.szerp.android.entity.User;
import com.szerp.android.util.JDBCUtils;
import net.sf.json.JSONObject;
public class LoginServletImpl extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
private JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource());
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
String username = request.getParameter("username").trim();
String passwd = request.getParameter("passwd").trim();
String password = PasswordUtil.encrypt(username, passwd, PasswordUtil.getStaticSalt());
//1获取JDBCTemplate 对象
String hql = "SELECT * FROM t_s_base_user u where u.userName = '"+username+"' and u.password = '"+password+"'";
List users = jdbcTemplate.query(hql, new BeanPropertyRowMapper<>(TSBaseUser.class));
JSONObject json = new JSONObject();
List list = new ArrayList<>();
if ((users != null) && (users.size() > 0)) {
TSBaseUser tsUser = (TSBaseUser)users.get(0);
System.out.println("userName==="+username);
System.out.println("passwd==="+passwd);
User user = new User();
user.setUserid("1");
user.setUsername(tsUser.getUserName());
user.setPasswd(tsUser.getPassword());
list.add(user);
json.put("data", list);
PrintWriter out = response.getWriter();
out.write(json.toString());//返回json数据
}else{
json.put("data", list);
PrintWriter out = response.getWriter();
out.write(json.toString());//返回json数据
}
}
}
(3)、建个跨域过滤器CorsFilter(public class CorsFilter implements Filter)
package com.szerp.android.controller;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response;
res.setContentType("text/html;charset=UTF-8");
res.setHeader("Access-Control-Allow-Origin", "*");//"*"所有域名可访问
res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
res.setHeader("Access-Control-Max-Age", "0");
res.setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token");
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader("XDomainRequestAllowed", "1");
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig config) throws ServletException {
}
@Override
public void destroy() {
}
}
(4)、配置一下web.xml
LoginServlet
com.android.service.impl.LoginServletImpl
LoginServlet
/LoginServlet
cors
com.android.controller
cors
/*
(1)、写个登录界面 activity_login.xml
(2)、再写点LoginActivity代码
请求网络数据需要权限,在manifest添加权限:
这里使用了 AsyncHttpClient 来请求 java后端 的数据
要在build里添加:
compile 'com.loopj.android:android-async-http:1.4.9'
LoginActivity
package com.example.peiming.a01;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import cz.msebera.android.httpclient.Header;
import entity.User;
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
AsyncHttpClient client;//异步加载
List ls_user = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Button button = (Button) findViewById(R.id.login_btn);
button.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.login_btn:
EditText idText= (EditText)findViewById(R.id.login_id);
EditText passwordText = (EditText) findViewById(R.id.login_password);
String username = idText.getText().toString();
String password = passwordText.getText().toString();
client = new AsyncHttpClient();//实例化AsyncHttpClient
//这里的IP(192.168.43.234:8080)要换成你自己电脑的IP !!!
String url = "http://192.168.2.199:8080/cmferp/LoginServlet?username=" + username + "&passwd=" + password;
ls_user = new ArrayList<>();//初始化
client.get(url, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
try {
JSONObject jsonObject = new JSONObject(new String(responseBody));
JSONArray jsonArray = jsonObject.getJSONArray("data");
for (int i=0; i= 3;
}
private boolean isPasswordValid(String password) {
return password.length() >= 6;
}
}
(4)、建个User类
package entity;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by ZhouJie on 2017/9/28.
*/
public class User {
private String userid;
private String account;
private String username;
private String passwd;
public User() {
}
public User(String userid, String account, String username, String passwd) {
this.userid = userid;
this.account = account;
this.username = username;
this.passwd = passwd;
}
public static User json2novel (JSONObject json) {
try {
return new User(json.getString("userid"),
json.getString("account"),
json.getString("username"),
json.getString("passwd")
);
}catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
}
友情例子
https://blog.csdn.net/u012964281/article/details/40625967