java 如何使用 HttpClient 将 XML 文件作为请求传递给我的 Servlet 之一?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17415698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I pass the XML file to one of my Servlet as the request using HttpClient?
提问by arsenal
Below is my code, in which I am trying to generate an XML file and then as soon as I generate an XML, I need to send this XML file to one of my own Servlet which is runnung locally on my box. I am able to generate an XML file but I am not sure how should I send that XML file to one of my servlet so that in the doGet method, I can parse that XML file.
下面是我的代码,我试图在其中生成一个 XML 文件,然后一旦我生成一个 XML,我就需要将此 XML 文件发送到我自己的一个 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.
}
My servlet is running locally on 8080. Below is the snippet from my servlet class-
我的 servlet 在 8080 上本地运行。下面是我的 servlet 类的片段-
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
BufferedReader reader = request.getReader();
//Parse the XML file here?
System.out.println(reader.readLine());
}
Updated Code:-
更新代码:-
I have created a Servlet class named SampleServlet
in a new dynamic web project
. I have started the server in debug mode. Below is the code in my Servlet-
我创建了一个以SampleServlet
新的dynamic web project
. 我已经在调试模式下启动了服务器。以下是我的 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());
}
And my web.xml file is like this-
而我的 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>
I have put the breakpoint in both the methods above. As soon as I hit this url from the browser-
我在上面的两种方法中都设置了断点。一旦我从浏览器点击这个网址 -
http://localhost:8080/ServletExample/SampleServlet
http://localhost:8080/ServletExample/SampleServlet
my breakpoint always gets hit in doGet method.
我的断点总是在 doGet 方法中被击中。
Now I have created a new Java Project in the eclipse which is my client and which will call the servlet doPost method as I need to pass an XML file to my servlet as a request.
现在我在 eclipse 中创建了一个新的 Java 项目,它是我的客户端,它将调用 servlet doPost 方法,因为我需要将 XML 文件作为请求传递给我的 servlet。
Below is my code-
下面是我的代码-
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);
}
But somehow as soon as I run my above main program as a Java Application, it doesn't hit the breakpoint I have put in my servlet class. And I am not sure why it is happening and no exceptions is getting thrown. Any idea why it is happening?
但是不知何故,只要我将上面的主程序作为 Java 应用程序运行,它就不会到达我在 servlet 类中放置的断点。而且我不确定为什么会发生这种情况并且没有抛出异常。知道为什么会这样吗?
采纳答案by Septem
Everything seems ok, I just copied your code into a new project
一切正常,我只是将您的代码复制到一个新项目中
public class SampleServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("doPost is called");
}
}
and run the client:
并运行客户端:
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);
}
}
the message "doPost is called" was printed in cosole, everything works as expected
消息“doPost被调用”打印在cosole中,一切都按预期工作
回答by Juned Ahsan
To post something to a servlet, using HTTP POST/doPost is a better option. GET/doGet is to get a resource. Here is the relevant code for the same:
要将某些内容发布到 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 Client code:
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();
}
}
回答by Septem
If it is not a "safe" method, you'd better use POST instead, then you can send xml in the body of post as below:
如果它不是一个“安全”的方法,你最好使用 POST 代替,然后你可以在 post 正文中发送 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);
If you'd rather use GET, one way to do this is to encode the xml in query string:
如果您更愿意使用 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);
parse xml in servlet:
在servlet中解析xml:
String xml = request.getParameter("xml");