我希望根据我拥有的原始数据发出HTTP post请求。我花了一段时间寻找解决方案,做了一些尝试,我正在寻找一些帮助。我正在寻找的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);
?>
我的尝试是这样的:
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;
}
然后执行postMethod,但这只是一个不包含数据的帖子。有人看到我在做什么错吗?我想弄清楚如何更改此方法以使其实际工作。谢谢!
-Ken
答案 0 :(得分:4)
java.net.URLConnection
班级不会更好吗?
答案 1 :(得分:1)
它看起来不像你在呼唤:
int result = httpclient.executeMethod(postMethod);
postMethod.releaseConnection();