java - HTTP POST 请求 XML 创建

标签 java android xml http-post

我想在 Android Activity 中发出 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);

我得到一个字符串文件(xml),它不是我应该得到的完整答案。如果我使用 Firefox 的 HTTP 资源测试,我会得到正确的答案,而使用我的解决方案,我会得到部分答案。当我删除

时,我设法在 HTTP 资源测试中收到相同的部分答案
<IAM version="1.0"> 

行或其他一些行(通常在“破坏”xml 结构时)。不过不知道有没有关系。

编辑(找到解决方案) 你能发现它吗? xml 结构中的第一个 RequestTimestamp 处缺少一个“>”。我整天都在复制粘贴,所以我没有提到它。噗……

最佳答案

你可以使用 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>

Source.

通过 http post 发送:

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();
    }

顺便说一句,请考虑使用 JSON而不是 XML。它更高效且更易于使用。

关于java - HTTP POST 请求 XML 创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11578793/

相关文章:

java - 如何将条目添加到 Java 中的现有 zip 文件?

java - #xD;和#13;读写 XML 文件时

java - ObjectMapper 正在尝试将字符串解析为 json 而不是 xml

java - Android 在内部根目录中创建文件夹

Java android baseAdapter 设置列表项一次

java - 使用FileSystemProvider实现FTP文件系统

xml - 如何在 XSLT 中使用 map ?

android - 两个 NFC 标签分别链接到项目中的两个不同 Activity ?

java - 如何在android中制作具有两种颜色的imageview边框并固定尺寸边框宽度

android - 在安卓 : How do I get variables/data from one screen to another?