0

我想创建一个应用程序,该应用程序将从 servlet 获取 JSON 对象以反序列化它,然后使用它的变量来做其他事情。

我的 servlet 在 doPost 中有以下代码:

 protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

      ObjectOutputStream os;
      os = new ObjectOutputStream(response.getOutputStream());

      String s = new String("A String");

      Gson gson = new Gson();
      String gsonObject= gson.toJson(s);

      os.writeObject(gsonObject);
      os.close();

    }

现在,当 servlet 运行时,我可以通过浏览器访问它,如果我在 doGet 方法中发布相同的代码,那将下载一个 servlet 文件,这不是我想要的。

我应该在我的第二个应用程序中使用什么来连接到 servlet,获取对象,以便以后可以操作它?

提前致谢。

4

3 回答 3

0

如果它下载 servlet 文件而不是在浏览器中显示它,很可能您没有在响应中设置内容类型。如果您正在编写 JSON 字符串作为 servlet 响应,则必须使用

response.setContentType("text/html");
response.getWriter().write(json);

请注意顺序,它的“text/html”而不是“html/text”

于 2012-12-09T05:02:12.473 回答
0

您需要对 servlet 进行一些更改:

protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
   String s = new String("A String");
 String json = new Gson().toJson(s);
 this.response.setContentType("application/json");
 this.response.setCharacterEncoding("UTF-8");
 Writer writer = null;
 try {
        writer = this.response.getWriter();
        writer.write(json);
 } finally {
    try {
        writer.close();
    } 
    catch (IOException ex) {
    }
 }
}
于 2012-12-09T05:50:15.910 回答
0

如果我正确理解了这个问题,那么您可以使用java.net.HttpURLConnectionjava.net.URL对象来创建与此 servlet 的连接,并在您的第二个 servlet 中读取上述 JSON servlet 流式传输的 JSON。

于 2012-12-09T06:19:54.987 回答