使用Java发布xml数据 [英] POST xml data using java
问题描述
我已使用以下Java代码将xml数据发布到远程URL并获取响应.在这里,我使用xml文件作为输入.我需要的是将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代码
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();
}
}
}
更新:我需要将XML作为字符串传递,并删除涉及的xml文件...
UPDATE: I need to pass XML as a string and remove involving xml file...
推荐答案
org.apache.commons.httpclient.methods.PostMethod上的setRequestEntity方法具有接受
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);
....
希望有帮助.
这篇关于使用Java发布xml数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!