Search code examples
javaandroidjsonservletsjsonexception

Value <html><head><title>Apache of type java.lang.String cannot be converted to JSONObject


I am sending json from servlet to android application , and the following exception occurs : -

 org.json.JSONException: Value <html><head><title>Apache of type java.lang.String cannot be converted to JSONObject

Following is my servlet code , please correct me if anything is wrong here :-

public class LoginCheck extends HttpServlet {

  protected void processRequest(HttpServletRequest request,  HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/json;charset=UTF-8");
    PrintWriter out = response.getWriter();


    JSONObject obj1 = new JSONObject();

    long uname =Long.parseLong(request.getParameter("mobile"));
    String pwd = request.getParameter("pass");

    try  {
    Connection con = new MyConnection().connect();
    PreparedStatement ps = con.prepareStatement("select * from bmt_user  where mobile_num=? and password=?");
    ps.setLong(1,uname);
    ps.setString(2,pwd);

     ResultSet rs=ps.executeQuery();

        if(rs.next())
       {
            obj1.accumulate("login","Success");
            out.println(obj1.toString());

       }

        else
        {
            obj1.accumulate("login","Fail");
            out.println(obj1.toString());
        }
       out.write(obj1.toString());     
    }catch(Exception e){out.println(e.toString());}
  }


  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, IOException {
     processRequest(request, response);
   }

   @Override
   protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
     processRequest(request, response);
  }

 }

Plus , when i assign the values to uname and pwd directly , without using request.getParameter() , the servlet runs just fine and returns json i.e

long uname = 48372984;
String pwd = "fabcd"

output -

{"login":"Fail"}

Solution

  • Your servlet code threw an uncaught exception which ended up in server default HTTP 500 error page in HTML flavor which has in case of Apache Tomcat server the below header:

    <!DOCTYPE html><html><head><title>Apache Tomcat/8.0.21 - Error report</title>
    

    That explains why the JSON parser in the client side flipped on it. Try reproducing the same in a normal webbrowser and you'll see the HTML error page in its entirety.

    Most likely the problem is at the below line:

    long uname = Long.parseLong(request.getParameter("mobile"));
    

    You're nowhere prechecking/catching a potential NullPointerException and NumberFormatException here. Read the server logs and fix the code accordingly. Perhaps the parameter name is wrong? Your local variable is named uname which doesn't sensibly match the request parameter name mobile.