views:

117

answers:

3

Hi All,

I'm looking to make an HTTP post request given the raw data that I have. I've spent a while looking for the solution, made a handful of attempts and I'm looking for a little bit of help. The PHP code for what I'm looking to do looks like this:

<?
$url="http://localhost:3000";
$postdata="<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<hi></hi>";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
$result = curl_exec($ch);
curl_close($ch);

echo($result);
?>

My attempt was this:

  private String setXmlPostHeader(Document doc, PostMethod postMethod) throws java.io.IOException, java.io.UnsupportedEncodingException,    
    javax.xml.transform.TransformerException
  {
     ByteArrayOutputStream xmlBytes = new ByteArrayOutputStream();
     XML.serialize( doc, xmlBytes );
     final byte[] ba = xmlBytes.toByteArray();
     String data = new String(ba, "utf-8");
     InputStreamRequestEntity re = new InputStreamRequestEntity(new ByteArrayInputStream(ba));
     postMethod.setRequestEntity(re);
     postMethod.setRequestHeader("Content-type", MediaType.XML.toString() + "; charset=UTF-8");
     return data;
  }

And then executing the postMethod, but this simply is a post containing no data. Does anyone see anything wrong that I'm doing? I'd like to figure out how to change this method to make it actually work. Thanks!

-Ken

A: 

Wouldn't the java.net.URLConnection class work better?

Here's an example.

duffymo
This worked like a charm. Exactly what I was looking for. Thanks so much!
Ken Mazaika
I'm glad it helped. Why not vote it up as well, then?
duffymo
I tried to, but I don't have the reputation to though. Sorry.
Ken Mazaika
You can't vote an answer up? I'll have to read the FAQs. It's been a while for me.
duffymo
+1  A: 

It doesnt look like you are calling:

    int result = httpclient.executeMethod(postMethod);  
    postMethod.releaseConnection();
Jataro
A: 

Maybe using StringEntity()..

DefaultHttpClient client = new DefaultHttpClient();

HttpPost httpost = new HttpPost("http://localhost:3000");
httpost.setEntity(new StringEntity(xmlString));
client.execute(httpost);
h3xStream