在 doPost 中获取 HttpServletRequestFilterable 响应

问题描述 投票:0回答:1

我正在使用 [Mailgun webhooks][1] 发送电子邮件,并使用以下 servlet 来捕获回发。

public class MyServlet extends HttpServlet {

  @Override

  public void doGet(HttpServletRequest request, HttpServletResponse response)

  throws ServletException, java.io.IOException {

    StringWriter stringWriter = new StringWriter();

    PrintWriter printWriter = new PrintWriter(stringWriter);

    printWriter.println("MyServlet");

    response.setContentType("text/plain");

    //response.setContentType("application/json");

    response.getOutputStream().print(stringWriter.toString());

  }

  @Override

  public void doPost(HttpServletRequest request, HttpServletResponse response)

  throws ServletException, java.io.IOException {

    System.out.println("HttpServletRequest below");

    System.out.println(request);

    System.out.println("HttpServletResponse below");

    System.out.println(response);

  }

在我的

doPost
中,我不断收到以下打印报表:

HttpServletRequest below
org.sitemesh.webapp.contentfilter.HttpServletRequestFilterable@4439aa1f

HttpServletResponse below
org.sitemesh.webapp.contentfilter.ContentBufferingFilter$1@4fa69476

这是什么意思?我期待一个 JSON 响应,因为他们在文档中提到他们正在发送 JSON 响应。 [1]:https://documentation.mailgun.com/en/latest/api-webhooks.html

java servlets
1个回答
0
投票

您在 doPost 方法中看到的输出表明您正在打印表示 HttpServletRequest 和 HttpServletResponse 的对象,而不是请求和响应的内容。

在您提供的代码中,这些行正在打印对象本身:`

System.out.println("HttpServletRequest below");
System.out.println(request);
System.out.println("HttpServletResponse below");
System.out.println(response);

要获取请求和响应的内容(其中应包含您期望的 JSON 数据),您应该访问请求和响应对象的方法和属性。

例如,如果您想访问请求的正文(JSON 数据),您可以执行以下操作:

public void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, java.io.IOException {
    BufferedReader reader = request.getReader();
    StringBuilder jsonRequest = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
        jsonRequest.append(line);
    }

    System.out.println("JSON Request:");
    System.out.println(jsonRequest.toString());
}

此代码从请求的输入流中读取 JSON 数据并打印它。也许这可以帮助:)

© www.soinside.com 2019 - 2024. All rights reserved.