简体   繁体   English

Java HTTP发布原始数据

[英]Java HTTP Post Raw Data

I'm looking to make an HTTP post request given the raw data that I have. 考虑到我拥有的原始数据,我希望发出一个HTTP发布请求。 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: 我要执行的PHP代码如下所示:

<?
$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. 然后执行postMethod,但这只是一个不包含数据的帖子。 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 -Ken

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

It doesnt look like you are calling: 它看起来不像您在打电话:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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