POST xml data using java

后端 未结 3 807
独厮守ぢ
独厮守ぢ 2021-02-14 21:04

I have used the following java code to POST xml data to a remote url and get the response. Here, I am using an xml file as the input. What I need is to pass the xml as a string

3条回答
  •  猫巷女王i
    2021-02-14 21:56

    You can convert the XML to String from this method

    public String convertXMLFileToString(String fileName) 
    { 
       try{ 
           DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); 
           InputStream inputStream = new FileInputStream(new File(fileName)); 
           org.w3c.dom.Document doc = documentBuilderFactory.newDocumentBuilder().parse(inputStream); 
           StringWriter stw = new StringWriter(); 
           Transformer serializer = TransformerFactory.newInstance().newTransformer(); 
           serializer.transform(new DOMSource(doc), new StreamResult(stw)); 
           return stw.toString(); 
       } 
       catch (Exception e) { 
           e.printStackTrace(); 
       } 
       return null; 
    }
    

    Add you can pass this string as a parameter on PostMethod like this.

    PostMethod post = new PostMethod(strURL);
    post.addParamter("paramName", convertXMLFileToString(strXMLFilename ) );
    

    The whole XML will be transmitted to the client in a queryString.

提交回复
热议问题