我使用以下java代码将xml数据POST到远程url并获取响应.在这里,我使用xml文件作为输入.我需要的是将xml作为字符串传递而不是文件...无论如何我能做到这一点吗?有人能帮我吗?非常感谢!
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
更新:我需要将XML作为字符串传递并删除涉及xml文件...
org.apache.commons.httpclient.methods.PostMethod上的setRequestEntity方法有一个重载版本,它接受StringRequestEntity作为参数.如果您希望将数据作为字符串传递(而不是输入流),则应使用此方法.所以你的代码看起来像这样:
String xml = "whatever.your.xml.is.here";
PostMethod post = new PostMethod(strURL);
try {
StringRequestEntity requestEntity = new StringRequestEntity(xml);
post.setRequestEntity(requestEntity);
....
Run Code Online (Sandbox Code Playgroud)
希望有所帮助.
| 归档时间: |
|
| 查看次数: |
37196 次 |
| 最近记录: |