如何使servlet与网站的API交互并存储XML响应?

时间:2010-12-02 06:26:10

标签: java jsp servlets

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String text = "some text";

    response.setContentType("text/plain");  // Set content type of the response so that jQuery knows what it can expect.
    response.setCharacterEncoding("UTF-8"); // You want world domination, huh?
    response.getWriter().write(text);       // Write response body.
}

如果我使用这个servlet,其中request变量将具有网站API的url。然后我如何捕获响应?我想知道这样做的代码是什么,在尝试构建一个处理与网站API交互并显示数据的JSP页面时,这是正确的方法吗?

1 个答案:

答案 0 :(得分:0)

你让事情变得混乱。 HttpServletRequest是客户端(webbrowser)为访问servlet而发出的HTTP请求。 HttpServletResponse是您应该用于将结果发送回客户端(webbrowser)的响应。

如果要以编程方式触发HTTP请求,则应使用java.net.URLConnection

URLConnection connection = new URL("http://example.com").openConnection();
InputStream input = connection.getInputStream(); // This contains the response. You need to convert this to String or some bean and then display in JSP.

另见: