我正在尝试使用 Json 格式和 Gson 库发送一些简单的字符串来测试我的 servlet 和 applet(servlet -> applet,而不是 applet -> servlet)之间的数据传输。小程序中的结果字符串应该与原始消息完全相同,但事实并非如此。我得到的是 9-character < !DOCTYPE字符串。
编辑:看起来servlet返回了HTML网页而不是JSON,不是吗?
edit2:在 NetBeans 中使用“运行文件”命令启动 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