Java Web服务器向Android客户端返回数据(服务器端)

时间:2022-12-02 08:49:07

结合我之前的文章 Android Java Web实现登录注册(一)——客户端点击打开链接

                                Android Java Web实现登录注册(二)——服务器端点击打开链接

Android客户端通过post方法调用web服务器的Servlet,post方法包含请求信息request和回答信息response,在服务器端Servlet的post方法中更新response,以达到向客户端返回信息的效果。

以下代码为客户端传来用户ID,服务器端返回用户信息(ID,用户名,密码)的示例,(服务器端)使用到 net.sf.json jar包中所有的.jar文件进行数据处理和传递,下载地址点击打开链接


UserInfoServlet.java(服务器端)

public class UserInfoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

public UserInfoServlet() {
super();
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
response.getWriter().append("Served at: ").append(request.getContextPath());
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 输出流
PrintWriter out = response.getWriter();
// 设置编码形式
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
// 获取传入的数据
String id = request.getParameter("id");
System.out.println("UserInfoServlet: id = " + id);

ArrayList<User> user_list =
new ArrayList<User>(new UserService().getInfo(id));
if(user_list.size() == 0){
out.print("NO_SUCH_USER");
}else{
JSONObject json = new JSONObject();
JSONArray jarray_u = new JSONArray();
try {
for(User user : user_list)
{

JSONObject user1 = new JSONObject();
user1.put("id", user.getId());
//解决中文乱码问题,服务器端加密,客户端解密
user1.put("username", URLEncoder.encode(user.getUsername(), "utf-8"));
user1.put("password", user.getPassword());jarray_u.add(user1);
}
json.put("users",jarray_u);
} catch (JSONException e) {
e.printStackTrace();
}
out.print(json.toString());
System.out.println("UserInfoServlet:" + json.toString());
}
out.flush();
out.close();
}
}

 

UserService.java(节选,服务器端)

 //根据id获取用户用户名、密码
public ArrayList<User> getInfo(String id) {
// 创建User对象数组
ArrayList<User> list= null;
list = new ArrayList <User>();
// SQL 语句:根据id查询
String sql = "select * from user_list where id = "+ id;
try {
// 获得数据库连接
Connection con = DBManager.getConnection();
// 获得语句对象
preparedStatement = con.prepareStatement(sql);
// 执行语句
resultSet = preparedStatement.executeQuery();
// 获取下一条记录
while (resultSet.next()){
System.out.println("UserService getInfo found");
User user = new User();
user.setId(resultSet.getString("id"));
user.setUsername(resultSet.getString("username"));
user.setPassword(resultSet.getString("password"));
list.add(user);
}
// 关闭结果
resultSet.close();
// 释放语句对象
preparedStatement.close();
// 关闭数据库连接
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}

启动Thread调用服务器端方法(节选,客户端)

// 访问数据库,通过id获取用户信息
public void getUserInfo(final String id) {
// 新建一个用于网络连接的线程,获取用户详细信息Thread
Log.i("tag", "getUserInfo");
new Thread() {
@Override
public void run() {
// Sevice传回Long
String responseMsg = "FAIL";
// 要发送的数据
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", id));
responseMsg = UserInfoPostService.send(params);
Log.i("tag", "MainAcitivity responseMsg : " + responseMsg);
// 准备发送消息
Message msg = handler.obtainMessage();
// 设置消息默认值
msg.what = 100;
if (responseMsg.equals("NO_SUCH_USER")) {
msg.obj = "用户不存在";
} else if (responseMsg.equals("FAIL")) {
msg.obj = "连接服务器失败";
} else {
// 解析JSON数据,存入本地数据库
try{
JSONObject jsonobject = new JSONObject(responseMsg.toString());
JSONArray ja_g = jsonobject.getJSONArray("users");
for (int i = 0; i < ja_g.length(); i++) {
JSONObject jsonobject2 = ja_g.getJSONObject(i);
UserItem user = new UserItem(jsonobject2.getString("id"),
jsonobject2.getString("username").toString(),
jsonobject2.getString("password").toString());
Message msg1 = handler.obtainMessage();
msg1.what = 333;
msg1.obj = user;
handler.sendMessage(msg1);
}
}catch(JSONException e){
e.printStackTrace();
}
}
handler.sendMessage(msg);
}
}.start();
}


处理Thread返回的消息(节选,客户端)

handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 333) {//得到详细用户信息
username = ((UserItem) msg.obj).getUsername();
Log.i("tag", "username: " + username);
} else {// 提示信息
//Toast.makeText(getApplicationContext(),(String)msg.obj,Toast.LENGTH_SHORT).show();
}
}
};


MyHttpPost.java (客户端)

和之前的代码相比,加上了解密的过程,解决中文乱码问题

public class MyHttpPost {
// 服务器地址
private static String SERVER = "http://123.207.3.202:8080";
// 项目地址
private static String PROJECT = "/SeeTogetherServer/";
// 请求超时
private static final int REQUEST_TIMEOUT = 0;
// 读取超时
private static final int SO_TIMEOUT = 0;

// 通过 POST 方式获取HTTP服务器数据
public static String executeHttpPost(String servlet, List<NameValuePair> params) {
String baseURL = SERVER + PROJECT + servlet;
String responseMsg = "FAILED";
try {
//连接到服务器端相应的Servlet
HttpPost request = new HttpPost(baseURL);
//request.addHeader("Content-Type", "application/json; charset=utf-8");
request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
BasicHttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
HttpClient client = new DefaultHttpClient(httpParams);
//client.getParams().setParameter("http.protocol.content-charset", "UTF-8");
HttpResponse response = client.execute(request);
if(response.getStatusLine().getStatusCode()==200)//是否成功收取信息
responseMsg = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
} catch (Exception e) {
e.printStackTrace();
}
Log.i("tag", "server" + SERVER);

try {//解密
Log.i("tag", "1 HttpPost: responseMsg = " + URLDecoder.decode(responseMsg,"utf-8"));
return URLDecoder.decode(responseMsg,"utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Log.i("tag", "2 HttpPost: responseMsg = " + responseMsg);
return responseMsg;
}
}