最近做了个Android请求获取Java后端数据的例子,简单实现了一下。
先上个登录界面图:
主要实现:
java后端的代码 + Android的代码
1、java后端
(1)、先创个User类
import net.sf.json.JSONObject;
public class User {
private long userid;
private String account;
private String username;
private String passwd;
public User(long 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.getLong("userid"),
json.getString("account"),
json.getString("username"),
json.getString("passwd")
);
}catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public long getUserid() {
return userid;
}
public void setUserid(long 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)
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 net.sf.json.JSONObject;
public class LoginServlet extends HttpServlet{
@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.se