I have a device which sends a JSON message via HTTP POST, to a web server. The server receives the JSON message as payload and decodes and prints it on the web page and also sends back a 200 OK response to the post.
Now, I am trying to replicate the same with a fake Java client code to act as the device and a fake server using servlet and JSP. The servlet code and JSP run as one project and the Java code run as another project.
I am using Eclipse and Tomcat server.
My code is as follows: Servlet Code: (This is saved in Java Resources > src > DefaultPackage)
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import org.json.JSONException;
import org.json.JSONObject;
@WebServlet("/HelloWorld")
public class HelloWorld extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
StringBuilder sb = new StringBuilder();
BufferedReader reader = request.getReader();
try {
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} finally {
reader.close();
}
System.out.println(sb.toString());
String api_key = null;
try {
//JSONObject jsonObj = new JSONObject(sb.toString().substring(sb.toString().indexOf('{')));
//JSONTokener t = new JSONTokener(sb.toString());
JSONObject obj = new JSONObject(sb.toString().replace("\uFEFF", ""));
System.out.println(obj.toString());
api_key= (String) obj.get("api_key");
//String node_number = (String) obj.get("node_number");
//String tag_statuses = (String) obj.get("tag_statuses");
//String voltage = (String) obj.get("voltage");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("api_key:"+ api_key+"\n");
response.setStatus(response.SC_OK);
//response.setContentType("text/html");
//PrintWriter out = response.getWriter();
//out.println("<h1>"+out +"</h1>");
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/NewFile.jsp");
request.setAttribute("api_key", api_key); // set your String value in the attribute
dispatcher.forward( request, response );
}
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
doPost(req, res);
}
}
JSP Code: (saved in WebContent)
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<table>
<tr>
<td><%=request.getAttribute("api_key")%></td>
</tr>
</table>
</body>
</html>
Java Application Code:
import java.io.*;
import java.net.*;
import org.json.JSONObject;
public class Client {
public static void main( String [] args ) {
try
{
JSONObject jsonObj = new JSONObject("{\"api_key\" : \"rien\", \"node_number\" : \"40\", \"tag_statuses\" : [[100,\"MISSING\"]], \"voltage\": \"345\", \"location\": [42.3432,23.0098]}");
URL url = new URL("http://localhost:95/sample/HelloWorld");
URLConnection uc = url.openConnection();
HttpURLConnection conn = (HttpURLConnection) uc;
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-type", "application/json");
PrintWriter pw = new PrintWriter(conn.getOutputStream());
//pw.write(jsonObj.toString());
pw.write(jsonObj.toString());
pw.close();
BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
bis.close();
int responseCode = conn.getResponseCode();
System.out.println("Response Code recieved is: " + responseCode);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Here, I would like to see the content received by the servlet to be updated on the JSP, whenever some new content appears on the servlet, maybe by refreshing the webpage.
Now, When I try to run the code, without a jsp page I am receiving the content from the application and the java application is getting a 200 status update.
But when I try to include the JSP code, the JSP will run and I get a 'null' printed on JSP, but I get the data on console of servlet and I get the following exception on Java application code (instead of a 200 status message),
java.io.FileNotFoundException: http://localhost:95/sample/HelloWorld
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at Client.main(Client.java:21)
Could someone please help me in getting the content printed on the JSP real time and to avoid the error on the Java application? What am I doing wrong here?
Thanks.