java HTTP POST 请求 XML 创建
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11578793/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTTP POST Request XML creation
提问by Thanos
I would like to make a HTTP POST request within an Android activity. I (think that I) know how to do so, but my problem is that I have no idea on how to create the XML file. I've tried different ways described in previous posts but I didn't manage to do so.
我想在 Android 活动中发出 HTTP POST 请求。我(认为我)知道该怎么做,但我的问题是我不知道如何创建 XML 文件。我尝试了以前帖子中描述的不同方法,但我没有设法这样做。
My xml format is the following:
我的xml格式如下:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<IAM version="1.0">
<ServiceRequest>
<RequestTimestamp>2012-07-20T11:10:12Z</RequestTimestamp
<RequestorRef>username</RequestorRef>
<StopMonitoringRequest version="1.0">
<RequestTimestamp>2012-07-20T11:10:12Z</RequestTimestamp>
<MessageIdentifier>12345</MessageIdentifier>
<MonitoringRef>112345</MonitoringRef>
</StopMonitoringRequest>
</ServiceRequest>
</IAM>
I have the following Java code lines written:
我编写了以下 Java 代码行:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
//What to write here to add the above XML lines?
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
EDIT
编辑
Although I managed to somehow create the xml using the following lines, the result I've got is not correct.
尽管我设法使用以下几行以某种方式创建了 xml,但我得到的结果不正确。
StringBuilder sb = new StringBuilder();
sb.append("<?xml version='1.0' encoding='UTF-8' standalone='yes'?>");
sb.append("<IAM version'1.0'>");
sb.append("<ServiceRequest>");
sb.append("<RequestTimestamp>2012-07-20T12:33:00Z</RequestTimestamp");
sb.append("<RequestorRef>username</RequestorRef>");
sb.append("<StopMonitoringRequest version='1.0'>");
sb.append("<RequestTimestamp>2012-07-20T12:33:00Z</RequestTimestamp>");
sb.append("<MessageIdentifier>12345</MessageIdentifier>");
sb.append("<MonitoringRef>32900109</MonitoringRef>");
sb.append("</StopMonitoringRequest>");
sb.append("</ServiceRequest>");
sb.append("</IAM>");
String xmlContentTosend = sb.toString();
StringEntity entity = new StringEntity(xmlContentTosend, "UTF-8");
httpPost.setEntity(entity);
httpPost.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials("username", "password"), "UTF-8", false));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
I get back a String file (xml) that it is not the whole answer that I should have. If I use the Firefox's HTTP Resource Test I get the correct answer while with my solution I get a partial one. I managed to receive the same partial answer in HTTP Resource Test when I removed the
我得到一个字符串文件 (xml),它不是我应该拥有的全部答案。如果我使用 Firefox 的 HTTP 资源测试,我会得到正确的答案,而我的解决方案会得到部分答案。当我删除
<IAM version="1.0">
line or some other lines (in general when "destroying" the structure of the xml). However I don't know if it is related.
行或其他一些行(通常在“破坏”xml 的结构时)。不过不知道有没有关系。
EDIT (Solution Found)Can you spot it? There's a missing ">" at the first RequestTimestamp in the xml structure. I've been copying-pasting the whole day so I haven't mentioned it. Pfff...
编辑(找到解决方案)你能发现吗?xml 结构中的第一个 RequestTimestamp 缺少 ">"。我一整天都在复制粘贴,所以我没有提到它。噗...
回答by Vinay W
you can do that using Dom parser
你可以使用 Dom 解析器来做到这一点
here's some code
这是一些代码
public class WriteXMLFile {
public static void main(String argv[]) {
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// root elements
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("company");
doc.appendChild(rootElement);
// staff elements
Element staff = doc.createElement("Staff");
rootElement.appendChild(staff);
// set attribute to staff element
Attr attr = doc.createAttribute("id");
attr.setValue("1");
staff.setAttributeNode(attr);
// shorten way
// staff.setAttribute("id", "1");
// firstname elements
Element firstname = doc.createElement("firstname");
firstname.appendChild(doc.createTextNode("yong"));
staff.appendChild(firstname);
// lastname elements
Element lastname = doc.createElement("lastname");
lastname.appendChild(doc.createTextNode("mook kim"));
staff.appendChild(lastname);
// nickname elements
Element nickname = doc.createElement("nickname");
nickname.appendChild(doc.createTextNode("mkyong"));
staff.appendChild(nickname);
// salary elements
Element salary = doc.createElement("salary");
salary.appendChild(doc.createTextNode("100000"));
staff.appendChild(salary);
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("C:\file.xml"));
// Output to console for testing
// StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
System.out.println("File saved!");
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
}
}
}
this creates an xml like
这会创建一个像
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<company>
<staff id="1">
<firstname>yong</firstname>
<lastname>mook kim</lastname>
<nickname>mkyong</nickname>
<salary>100000</salary>
</staff>
</company>
to send it via an http post :
通过 http 帖子发送:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.192.131/");
try {
StringEntity se = new StringEntity( "<aaaLogin inName=\"admin\" inPassword=\"admin123\"/>", HTTP.UTF_8);
se.setContentType("text/xml");
httppost.setEntity(se);
HttpResponse httpresponse = httpclient.execute(httppost);
HttpEntity resEntity = httpresponse.getEntity();
tvData.setText(EntityUtils.toString(resEntity));
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and btw, Consider using JSONinstead of XML. It's more efficient and easier to use.
顺便说一句,考虑使用JSON而不是 XML。它更高效,更易于使用。
回答by Pranab Thakuria
Using java want to create an http POST request in xml like below:
使用java想要在xml中创建一个http POST请求,如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<xmlActivityRequest version="2.0" xmlns="http://www.request.com/schema">
<authentication>
<user>pranab</user>
<password>pranab</password>
</authentication>
<actionDate>2019-03-28</actionDate>
<transactionOnly>false</transactionOnly>
</xmlActivityRequest>
So, here is the code.
所以,这是代码。
public String prepareRequest(String actionDate, String username, String password) {
Document xmldoc = null;
Element e = null;
Element sube = null;
Node n = null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
DOMImplementation impl = builder.getDOMImplementation();
xmldoc = impl.createDocument(null, "xmlActivityRequest", null);
Element root = xmldoc.getDocumentElement();
root.setAttribute("version", "2.0");
root.setAttribute("xmlns", "http://www.request.com/schema");
e = xmldoc.createElement("authentication");
sube = xmldoc.createElement("user");
n = xmldoc.createTextNode("pranab");
sube.appendChild(n);
e.appendChild(sube);
sube = xmldoc.createElement("password");
n = xmldoc.createTextNode("pranab");
sube.appendChild(n);
e.appendChild(sube);
root.appendChild(e);
e = xmldoc.createElement("actionDate");
n = xmldoc.createTextNode("2019-03-28");
e.appendChild(n);
root.appendChild(e);
e = xmldoc.createElement("transactionOnly");
n = xmldoc.createTextNode("false");
e.appendChild(n);
root.appendChild(e);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
OutputFormat outputformat = new OutputFormat();
outputformat.setIndent(4);
outputformat.setIndenting(true);
outputformat.setPreserveSpace(false);
XMLSerializer serializer = new XMLSerializer();
serializer.setOutputFormat(outputformat);
serializer.setOutputByteStream(stream);
serializer.asDOMSerializer();
serializer.serialize(xmldoc.getDocumentElement());
return stream.toString();
} catch (ParserConfigurationException e) {
LOGGER.error("Unable to create a Parser that produces DOM object trees from
transactionOnly XML documents " + e.getMessage());
} catch (IOException e) {
LOGGER.error("Unable to find the Document Element " + e.getMessage());
}
return null;
}
For more visit: https://programmingproblemsandsolutions.blogspot.com/2019/03/using-java-want-to-create-http-post.html
更多信息请访问:https: //programmingproblemsandsolutions.blogspot.com/2019/03/using-java-want-to-create-http-post.html