简体   繁体   中英

HTTP POST Request XML creation

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.

My xml format is the following:

<?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:

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.

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

<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.

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...

you can do that using Dom parser

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>

Source.

to send it via an 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();
    }

and btw, Consider using JSON instead of XML. It's more efficient and easier to use.

Using java want to create an http POST request in xml like below:

        <?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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM