简体   繁体   中英

Java HTTP Post Raw Data

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

java.net.URLConnection类不能更好地工作吗?

It doesnt look like you are calling:

    int result = httpclient.executeMethod(postMethod);  
    postMethod.releaseConnection();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM