我想在Android活动中发出HTTP POST请求。我(认为我)知道如何这样做,但我的问题是我不知道如何创建XML文件。我尝试过以前的帖子中描述的不同方式,但我没有设法这样做。
我的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>
我编写了以下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);
编辑
虽然我设法以某种方式使用以下行创建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);
我找回一个String文件(xml),这不是我应该拥有的全部答案。如果我使用Firefox的HTTP资源测试,我得到了正确的答案,而我的解决方案我得到了一个部分答案。当我删除时,我设法在HTTP资源测试中收到相同的部分答案
<IAM version="1.0">
行或其他一些行(通常在“破坏”xml的结构时)。但是我不知道它是否相关。
编辑(找到解决方案)你能发现它吗?在xml结构中的第一个RequestTimestamp处缺少“>”。我一直在复制粘贴,所以我没有提到它。 Pfff ...
你可以使用Dom解析器做到这一点
这是一些代码
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();
}
}
}
这会创建一个xml
<?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>
通过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();
}
和btw,考虑使用JSON而不是XML。它更有效,更易于使用。
使用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>
所以,这是代码。
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;
}
欲了解更多信息,请访问:https://programmingproblemsandsolutions.blogspot.com/2019/03/using-java-want-to-create-http-post.html