Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST xml data using java

Tags:

java

post

xml

I have used the following java code to POST xml data to a remote url and get the response. Here, I am using an xml file as the input. What I need is to pass the xml as a string not a file... is there anyway I can do this? Can someone help me? Thanks a lot!

Java code

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;

public class xmlToString {

public static void main(String[] args) {
    String strURL = "https://simulator.expediaquickconnect.com/connect/ar";
    String strXMLFilename = "xmlfile.xml";
    File input = new File(strXMLFilename);
    PostMethod post = new PostMethod(strURL);
    try {
        post.setRequestEntity(new InputStreamRequestEntity(
                new FileInputStream(input), input.length()));
        post.setRequestHeader("Content-type",
                "text/xml; charset=ISO-8859-1");
        HttpClient httpclient = new HttpClient();

        int result = httpclient.executeMethod(post);
        System.out.println("Response status code: " + result);
        System.out.println("Response body: ");
        System.out.println(post.getResponseBodyAsString());
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        post.releaseConnection();
    }
}

   }

UPDATE: I need to pass XML as a string and remove involving xml file...

like image 866
Pavithra Gunasekara Avatar asked Jul 05 '11 09:07

Pavithra Gunasekara


1 Answers

The setRequestEntity method on org.apache.commons.httpclient.methods.PostMethod has an overloaded version that accepts StringRequestEntity as argument. You should use this if you wish to pass in your data as a string (as opposed to an input stream). So your code would look something like this:

String xml = "whatever.your.xml.is.here";
PostMethod post = new PostMethod(strURL);     
try {
    StringRequestEntity requestEntity = new StringRequestEntity(xml);
    post.setRequestEntity(requestEntity);
....

Hope that helps.

like image 117
Perception Avatar answered Oct 15 '22 23:10

Perception