0

I am trying to use httpclient to post xml request as following:

String parm1 = MyXml.toString();
PostMethod post = new Postmethod(url);
post.setRequestEntity(new StringRequestEntity(parm1));
...

I have an object in the program which I want to convert it to xml representation.

My question is that what is the best way to create Myxml in xml format in java which then I can simply print out its String format later.

Thanks.

Lukas Knuth
  • 25,449
  • 15
  • 83
  • 111
Tony
  • 3,319
  • 12
  • 56
  • 71
  • 1
    Are you asking for the best way to create a `toXML()` method or are you asking something about the technique for POSTing data? – Larry OBrien Jul 09 '12 at 19:08
  • I am more interested in creating a xml that later I can use it to pass in parameter for the http post. So, I guess I am kinda asking both. – Tony Jul 09 '12 at 19:17
  • you could look at http://www.mkyong.com/tutorials/java-xml-tutorials/ for the XML part. – OVB Jul 09 '12 at 19:21

3 Answers3

0

There are many options for creating XML in Java. This answer How to serialize and de-serialize objects using JAXB? provides a good demo of one common way that seems to fit your use-case.

Community
  • 1
  • 1
Larry OBrien
  • 8,484
  • 1
  • 41
  • 75
0

Here is how you can post xml request using Apache HttpClient.

  • Use apache Velocity to create the request xml format
  • Use Castor to convert response stream( respReader ) into java object

    final String request = createXmlRequest(); // helper method to create the xml request
    final HttpClient client = new HttpClient();
    final PostMethod post = new PostMehod(url); // url - www.google.cm/someoperaion
    
    post.setRequestHeader("Content-Language", "en-US");
    post.setRequestEntity(new StringRequestEntity(request, "text/xml", "ISO-8859-1"));
    
    final int returnCode = client.executeMethod(post);
    
    final BufferedReader respReader = new BufferedReader(new InputStreamReader(post.getResponseBodyAsStream()));
    
Chand
  • 91
  • 4
-1

Try to use it this way...

public void postData() throws Exception {


 HttpClient client = new DefaultHttpClient();
 HttpPost httppost = new HttpPost("https://www.xyz.com");

 List<NameValuePair> list = new ArrayList<NameValuePair>(1);

 list.add(new BasicNameValuePair("name","ABC");

 httppost.setEntity(new UrlEncodedFormEntity(list));

 HttpResponse r = client.execute(httppost);

}
Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75