我试图发送一些简单的字符串来测试我的servlet和小应用程序之间的数据传输 (servlet - > applet,而不是applet - > servlet),使用Json格式和Gson库。 小程序中产生的字符串应该与原始消息完全相同,但事实并非如此。 我得到9个字符<!DOCTYPE字符串代替。JSON反序列化失败? (servlet->小程序通信)
编辑:它看起来像servlet返回的HTML网页,而不是JSON,不是吗?
edit2:在NetBeans中使用“运行文件”命令激活servlet时,消息在浏览器中正确显示。
能否请你在我的代码来看看:
的Servlet:
//begin of the servlet code extract
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter();
try
{
String action;
action = request.getParameter("action");
if ("Transfer".equals(action))
{
sendItToApplet(response);
}
}
finally
{
out.close();
}
}
public void sendItToApplet(HttpServletResponse response) throws IOException
{
String messageToApplet = new String("my message from the servlet to the applet");
String json = new Gson().toJson(messageToApplet);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
Writer writer = null;
writer = response.getWriter();
writer.write(json);
writer.close();
}
//end of the servlet code extract
小程序:
//begin of the applet code extract
public void getItFromServlet() throws MalformedURLException, IOException, ClassNotFoundException
{
URL urlServlet = new URL("http://localhost:8080/Srvlt?action=Transfer");
URLConnection connection = urlServlet.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestProperty("Content-Type", "application/json");
InputStream inputStream = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
JsonReader jr = new JsonReader(br);
String retrievedString = new Gson().fromJson(jr, String.class);
inputStream.close();
jtextarea1.setText(retrievedString); //jtextarea is to display the received string from the servlet in the applet
}
//end of the applet code extract
那么......当您使用浏览器或curl测试时,您的servlet会返回什么结果? –
它返回的是简单格式的页面,其值为“String messageToApplet”,仅此而已。 – BMC
如果您只需要在Servlet和Applet之间传输一个字符串,那么使用JSON并不是必需的,而是一个开销。顺便说一句,你需要清理你的代码。 –