【发布时间】:2018-06-11 16:20:45
【问题描述】:
我正在编写一个使用 java Servlet 管理登录的 Android 应用程序。 在 MySQL 数据库中检查登录数据。 这个 servlet 应该返回一个 json 对象。 下面是一些代码:
小服务程序:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package AndroidControllers;
import Database.Authentication;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.JSONObject;
/**
*
* @author serge
*/
public class Android extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet Android</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet Android at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
PrintWriter writer = response.getWriter();
String user = request.getParameter("username");
String pass = request.getParameter("password");
PrintWriter out = response.getWriter();
JSONObject logged = Authentication.login_json(user, pass);
if(logged != null)
writer.print(logged);
else{
logged.put("type", "ERROR");
logged.put("username", "ERROR");
writer.print(logged);
}
//processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
Authentication.login_json 方法:
public static JSONObject login_json(String user, String pass){
JSONObject json = new JSONObject();
Connection conn = null;
String sql = "select username, user_type from users where username = '" + user +
"' and password = '" + pass + "';";
try{
Class.forName("com.mysql.jdbc.Driver");
conn = Utilities.connect();
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(sql);
if(rs.next()){
json.put("username", user);
json.put("type", rs.getString("user_type"));
}
else{
json.put("username", "FAIL");
json.put("type", "FAIL");
}
}
catch(SQLException | ClassNotFoundException ecc){
System.out.println("ERROR: " + ecc.getMessage());
}
finally{
Utilities.disconnect(conn);
}
return json;
}
Android中使用的认证方式:
package com.example.serge.biblioteca;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class http_authentication{
public static JSONObject login_json(String user, String pass) {
String json_string = "";
JSONObject stream = new JSONObject();
JSONParser parser = new JSONParser();
String url = "http://localhost:43746/Progetto_TWEB/Android?username=" + user
+ "&password=" + pass;
try {
URL link = new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection) link.openConnection();
// Check the connection status
if (urlConnection.getResponseCode() == 200) {
// if response code = 200 ok
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
// Read the BufferedInputStream
BufferedReader r = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
sb.append(line);
}
json_string = sb.toString();
stream = (JSONObject) parser.parse(json_string);
// End reading...............
// Disconnect the HttpURLConnection
urlConnection.disconnect();
} else {
// Do something
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} finally {
}
// Return the data from specified url
return stream;
}
}
在普通 Java 类中使用的这些方法效果很好,它们总是返回预期的 json 对象。在 Andoid 应用程序中,我总是得到一个空的 json 对象,我不知道为什么。
这是活动代码:
package com.example.serge.biblioteca;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.json.simple.parser.JSONParser;
import org.json.simple.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
/**
* Created by serge on 28/12/2017.
*/
public class login extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final Button login = (Button) findViewById(R.id.login_login);
final EditText username = (EditText) findViewById(R.id.txtUser);
final EditText password = (EditText) findViewById(R.id.txtPass);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
JSONObject logged = new JSONObject();
boolean vuoto = false;
String logged_type = "";
String logged_user = "", user_type = "";
TextView welcome = (TextView)findViewById(R.id.normal_intro);
String user = username.getText().toString();
String pass = password.getText().toString();
try {
logged = http_authentication.login_json(user, pass);
vuoto = logged.isEmpty();
//The following setText always returns an empty String so I think the object is null
username.setText(logged.toString());
}
catch(Exception ecc){
username.setText(ecc.getMessage());
}
}
});
}
}
你们能帮我理解为什么 Android Activity 总是得到一个空对象,但是一个普通的 java 类工作得很好吗? 谢谢
【问题讨论】:
-
您遇到错误了吗?
-
没有错误,我只是得到一个空字符串
-
"login_json"方法调用后"json_string"为空?
-
是的,我也尝试修改方法以返回相同的内容,但作为字符串返回。在普通 Java 类中运行良好,在 Android Activity 中始终为空/null
-
这个问题有很多噪音,你可以自己总结一下。可以省略一半以上的代码,以澄清问题并为自己放大实际问题。此问题与 JSON 对象无关。此问题与登录无关。这个问题与 servlet 正在做什么无关,即使它只是返回一个“Hello World”测试字符串。您应该注意 getResponseCode() 是否真的返回 200 以及异常日志记录。您应该一遍又一遍地问自己,servlet URL 中的“localhost”到底是什么意思。
标签: java android json servlets