0

我想在 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);

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

<IAM version="1.0"> 

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

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

4

2 回答 2

4

你可以使用 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 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();
    }

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

于 2012-07-20T12:57:25.780 回答
0

使用 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

于 2019-03-29T07:28:20.333 回答