【问题标题】:How can I pass the XML file to one of my Servlet as the request using HttpClient?如何使用 HttpClient 将 XML 文件作为请求传递给我的 Servlet 之一?
【发布时间】:2013-06-29 05:41:08
【问题描述】:

下面是我的代码,我在其中尝试生成一个 XML 文件,然后在生成 XML 后,我需要将此 XML 文件发送到我自己的一个 Servlet,该 Servlet 在我的机器上本地运行。我能够生成一个 XML 文件,但我不确定应该如何将该 XML 文件发送到我的一个 servlet,以便在 doGet 方法中,我可以解析该 XML 文件。

public static void main(String[] args) throws SAXException, XPathExpressionException, ParserConfigurationException, IOException,
    TransformerException {

String xml = generateXML();
send("http://localhost:8080/ServletExample/SampleServlet", xml);
}


/**
 * A simple method to generate an XML file
 *
 */  
public static String generateXML(String conn, String funcAddr) throws ParserConfigurationException, SAXException, IOException,
    XPathExpressionException, TransformerException {

DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

// Some code here to make an XML file

String xmlString = sw.toString();

// print xml
System.out.println("Here's the xml:\n" + xmlString);

return xmlString;
}


/**
 * A simple method to send the XML to servlet class
 *
 */
public static void send(String urladdress, String file) throws MalformedURLException, IOException {
String charset = "UTF-8";
String s = URLEncoder.encode(file, charset);

// I am not sure what should I do here so that I can pass the 
//  above XML file that I made to my servlet class.

}

我的 servlet 在 8080 本地运行。下面是我的 servlet 类中的 sn-p-

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

    BufferedReader reader = request.getReader();

    //Parse the XML file here?

    System.out.println(reader.readLine());

}

更新代码:-

我在新的dynamic web project 中创建了一个名为SampleServlet 的Servlet 类。我已经在调试模式下启动了服务器。下面是我的 Servlet 中的代码-

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

    BufferedReader reader = request.getReader();
    System.out.println(reader.readLine());

}

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

    BufferedReader b = new BufferedReader(request.getReader());  
    System.out.println(reader.readLine());

}

而我的web.xml文件是这样的-

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>ServletExample</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description></description>
    <display-name>SampleServlet</display-name>
    <servlet-name>SampleServlet</servlet-name>
    <servlet-class>com.servlet.example.SampleServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>SampleServlet</servlet-name>
    <url-pattern>/SampleServlet</url-pattern>
  </servlet-mapping>
</web-app>

我在上述两种方法中都设置了断点。一旦我从浏览器中点击此网址-

http://localhost:8080/ServletExample/SampleServlet

我的断点总是在 doGet 方法中被命中。

现在我在 eclipse 中创建了一个新的 Java 项目,它是我的客户端,它将调用 servlet doPost 方法,因为我需要将 XML 文件作为请求传递给我的 servlet。

下面是我的代码-

public static void main(String[] args) {

    HttpPost post = new HttpPost("http://localhost:8080/ServletExample/SampleServlet");
    post.setHeader("Content-Type", "application/xml");
    post.setEntity(new StringEntity(generateNewXML()));
    HttpClient client = new DefaultHttpClient();
    HttpResponse response = client.execute(post);
}

但不知何故,一旦我将上面的主程序作为 Java 应用程序运行,它就不会命中我在 servlet 类中放置的断点。而且我不确定它为什么会发生,并且没有抛出异常。知道为什么会这样吗?

【问题讨论】:

    标签: java xml servlets request


    【解决方案1】:

    一切正常,我刚刚将您的代码复制到一个新项目中

    public class SampleServlet extends HttpServlet {
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            System.out.println("doPost is called");
        }
    }
    

    并运行客户端:

    public class PostClient {
    
        public static void main(String[] args) throws ClientProtocolException, IOException {
            HttpPost post = new HttpPost("http://localhost:8080/ServletExample/SampleServlet");
            post.setHeader("Content-Type", "application/xml");
            post.setEntity(new StringEntity("<xml></xml>"));
            HttpClient client = new DefaultHttpClient();
            HttpResponse response = client.execute(post);
        }
    
    }
    

    消息“doPost is called”已打印在 cosole 中,一切正常

    【讨论】:

    • PostClient 在哪个包中?这完全是一个不同的项目,对吧?
    • 与 SampleServlet 所在的包是同一个包,但它与您放置客户端代码的位置无关
    • 没错。但是为什么它没有击中我的 servlet 代码。我正在执行与上述相同的步骤。您如何启动 servlet,您确实添加和删除并添加了您的 servlet 对吗?然后以调试模式启动服务。正确的?然后您将主程序作为 Java 应用程序运行。对吗?
    • Aaah.. 这就是我得到的java.net.SocketException: Software caused connection abort: recv failed 知道为什么会这样吗?
    • 我没有在调试模式下运行服务器。你确定 doPost 没有被调用吗?尝试输入“System.out.println("doPost is called");"在doPost方法中,看看是否打印在cosole中?
    【解决方案2】:

    要将某些内容发布到 servlet,使用 HTTP POST/doPost 是更好的选择。 GET/doGet 是获取资源。这是相同的相关代码:

    Servlet doPost

    public void doPost(HttpServletRequest req,  
                        HttpServletResponse res)  
          throws ServletException, IOException {  
          try {  
                BufferedReader b = new BufferedReader(req.getReader());  
                StringBuffer xmlBuffer = new StringBuffer();    
                String xmlString = "";          
                while((xmlString = b.readLine()) != null) {  
                       xmlBuffer.append(xmlString);  
                }  
                xmlString = xmlBuffer.toString();  
                if (workBuffer.length() > 0) {  
                  System.out.println("Got XML: " + workString);  
                }      
                else {  
                     System.out.println("No XML document received");  
                }  
          }   
    

    Http POST 客户端代码:

    private void postMessage(TextMessage xmlMsg, String urlString)  
                    throws Exception  
    {  
      try  
      {  
        URL url = new URL(urlString);  
        URLConnection uc = url.openConnection();  
        HttpURLConnection conn = (HttpURLConnection) uc;  
        conn.setDoInput(true);  
        conn.setDoOutput(true);  
        conn.setRequestMethod("POST");  
        conn.setRequestProperty("Content-type", "text/xml");          
        PrintWriter pw = new PrintWriter(conn.getOutputStream());  
        pw.write(xmlMsg.getText());  
        pw.close();  
        BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());  
        bis.close();  
    
      }  
      catch (Exception e)  
      {  
        e.printStackTrace();  
      }  
    }   
    

    【讨论】:

    • 感谢 Juned 的建议。在您的 doPost 方法中,workBuffer 和 workString 是什么?我不清楚。您能否相应地更新它。我也试过你的建议。我在调试模式下启动了 servlet 服务器。并将断点放在 doPost 方法中。它没有进去,卡在这条线上BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
    【解决方案3】:

    如果不是“安全”的方法,你最好使用 POST 代替,然后你可以在 post 的 body 中发送 xml,如下:

    HttpPost post = new HttpPost("http://localhost:8080/ServletExample/SampleServlet");
    post.setHeader("Content-Type", "application/xml");
    post.setEntity(new StringEntity(generateXML()));
    HttpClient client = new DefaultHttpClient();
    HttpResponse response = client.execute(post);
    

    如果您更愿意使用 GET,一种方法是在查询字符串中编码 xml:

    String xml = generateXML();
    HttpGet get = new HttpGet("http://localhost:8080/ServletExample/SampleServlet?xml=" + URLEncoder.encode(xml, "UTF-8"));
    HttpClient client = new DefaultHttpClient();
    HttpResponse response = client.execute(get);
    

    在 servlet 中解析 xml:

    String xml = request.getParameter("xml"); 
    

    【讨论】:

    • 感谢 Septem 的建议。我在我的 servlet 所在的调试模式下启动了服务器。关于客户端代码,我从一个主要方法运行它。一旦我运行 main 方法,它就没有命中我的 servlet。我已将断点放在我的 doPost 方法中,但它并没有到达那里。知道为什么吗?
    • 还有如何使用这样的? String xml = request.getParameter("xml"); 你是怎么得到请求中的xml标签的?
    • 如果你想调用 doPost(),你必须发送一个 post 请求,比如:client.execute(post)
    • 你可以使用一些xml解析器比如SAX、dom4j来获取你想要的xml标签
    • 这就是我对您的第一条评论所做的,它没有影响我的 servlet。那就是我想知道为什么会发生在我身上的原因。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    • 2020-01-29
    相关资源
    最近更新 更多