How can I pass the XML file to one of my Servlet as the request using HttpClient?
Solution 1
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
Solution 2
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 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:
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();
}
}
Solution 3
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:
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:
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:
String xml = request.getParameter("xml");
arsenal
profile for ferhan on Stack Exchange, a network of free, community-driven Q&A sites http://stackexchange.com/users/flair/335839.png
Updated on June 05, 2022Comments
-
arsenal almost 2 years
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.
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-
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 newdynamic web project
. I have started the server in debug mode. Below is the code in my 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-
<?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
my breakpoint always gets hit in doGet method.
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.
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?
-
arsenal almost 11 yearsThanks Juned for the suggestion. In your doPost method what is workBuffer and workString? It's not clear to me. Can you please update it accordingly. And also I have tried your suggestion. I started the servlet server in debug mode. And put the breakpoint in doPost method. It is not going inside and it got stuck on this line
BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
-
arsenal almost 11 yearsThanks Septem for the suggestion. I started the server in debugging mode where my servlet is. And regarding the client code, I am running it from a main method. As soon as I run the main method, it is not hitting my servlet. I have put the breakpoint in my doPost method and it is not hitting there. Any idea why?
-
arsenal almost 11 yearsAnd also how are using like this?
String xml = request.getParameter("xml");
how did you got xml tag in the request? -
Septem almost 11 yearsIf you want doPost() to be called, you have to send a post request like: client.execute(post)
-
Septem almost 11 yearsYou can use some xml parser such SAX, dom4j to get xml tag you want
-
arsenal almost 11 yearsThat's what I did to your first comment and it is not hitting my servlet. That;s what I am wondering why it is happening to me.
-
Septem almost 11 yearsThen I need more details to find out where the problem is, can you post your client, servlet code and web.xml?
-
arsenal almost 11 years
-
arsenal almost 11 yearsPostClient is in which package? It's a different project alltogether right?
-
Septem almost 11 yearsIt is the same package where SampleServlet is, but it has nothing to do with where you put your client code
-
arsenal almost 11 yearsExactly. But why it is not hitting my servlet code then. I am exactly doing the same above steps. How are you starting the servlet, you did add and remove and added your servlet right? And then started the served in debug mode. Right? And then you ran your main program as Java Application. Right?
-
arsenal almost 11 yearsAaah.. That's what I got
java.net.SocketException: Software caused connection abort: recv failed
Any idea why it is happening? -
Septem almost 11 yearsI am not running server in debug mode. Are you sure doPost is not called? Try to put "System.out.println("doPost is called");" in doPost method and see if it is printed in cosole?
-
arsenal almost 11 yearsI did that as well, its not getting called. This is what I am getting-
java.net.SocketException: Software caused connection abort: recv failed
. Any idea why it is happening? -
Septem almost 11 yearsIs your client code behind some firewall or proxy? Try turn them off