HTTP POST Request XML creation

22,027

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.

Share:
22,027
Admin
Author by

Admin

Updated on March 30, 2020

Comments

  • Admin
    Admin about 4 years

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

    • Kumar Bibek
      Kumar Bibek almost 12 years
      What is the response you are getting?
  • Admin
    Admin almost 12 years
    The server that I send the request is not mine. As far as I know they only accept xml.
  • Admin
    Admin almost 12 years
    Ok, I created the Document. How do I create from it the entity to add to the httpPost?
  • Admin
    Admin almost 12 years
    thanks for your answers. I've tried everything. If you check my question, the problem is that I don't receive the whole answer from the server. I don't know why this is happening. When I use the HTTP Resource Test on Firefox, everything is running fine. When I try it on my own I receive a partial answer.