Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Creating XML response in Java

Posted on 2009-12-28
5
Medium Priority
?
2,335 Views
Last Modified: 2013-12-17
Hi,
I've writen this code which sends XML from one server to another. I need to write code which will generate XML repsonse and sent is back to client.... Below is is my client and Server code...
The line in my server code where it says //Generate the XML response back. will send response back to clint after building the XML
XML Response to be build:
<?xml version="1.0" encoding="ISO-8859-1"?>
<response>
  <Status code="101" text="Accepted">Acknowledged</Status>
</response>

Code:
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;


public class TestPost {

      /**
       * @param args
       */
      @SuppressWarnings("deprecation")
      public static void main(String[] args) {
            // TODO Auto-generated method stub

            String inputString = "";
            String input;
            try {
                  BufferedReader in = new BufferedReader(new FileReader(
                              "c:\\Java_J2ee\\MyXMLFile.xml"));
                  while ((input = in.readLine()) != null)
                        inputString = inputString + input;

                  System.out.println("Input String is " + inputString);
                  in.close();

                  URL ASNServerURL = new URL("http://localhost:8080/ABCMockServer");
                  HttpURLConnection c = (HttpURLConnection) (ASNServerURL
                              .openConnection());
                  c.setDoOutput(true);

                  PrintWriter out = new PrintWriter(c.getOutputStream());
                  // Here's whether the parameter is set.
                  // out.println("xmldoc=" + URLEncoder.encode(inputString));
                  out.println("xmldoc=" + URLEncoder.encode(inputString, "UTF-8"));
                  out.close();

                  BufferedReader in2 = new BufferedReader(new InputStreamReader(c
                              .getInputStream()));

                  String inputLine;
                  while ((inputLine = in2.readLine()) != null)
                        System.out.println(inputLine);
                  in2.close();

            } catch (Exception e) {

                  e.printStackTrace();

            }

      }

}
 Server CODE
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // TODO Auto-generated method stub
      
            System.out.println("Inside ASNMockServer");
            response.setContentType("text/plain");
        PrintWriter out = response.getWriter();

        HttpSession session = request.getSession();

        String xml = request.getParameter("xmldoc");
        checkIfXMLIsWellFormed(xml);
        //out.println(xml);
      
      }
      
      
      public void checkIfXMLIsWellFormed(String aXml){
            
            try{
                  
                  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                  InputSource source = new InputSource( new StringReader(aXml));
                  Document document = factory.newDocumentBuilder().parse(source);
                  
                  System.out.println("XML Is well-formed");
                  
                  //Generate the XML response back
                  
                  
            } catch(ParserConfigurationException e){
                  
                        System.out.println( aXml + "Is not well-formed");
                  
            }
            catch(SAXException se){
                  
                        System.out.println(se.getMessage());
                    

            }
            catch(IOException io){
                  
                  System.out.println(io.getMessage());
            }
            
      }



0
Comment
Question by:AjooAli
  • 3
  • 2
5 Comments
 
LVL 92

Expert Comment

by:objects
ID: 26134457
whats wrong with out.println(xml); as you have commented out

0
 

Author Comment

by:AjooAli
ID: 26134570
Thanks,
Nothing wrong with it.. What I'm trying to do is to create a new XML response and send it back to Client.

XML Response:
<?xml version="1.0" encoding="ISO-8859-1"?>
<response>
  <Status code="101" text="Accepted">Acknowledged</Status>
</response>
 
0
 

Author Comment

by:AjooAli
ID: 26134608
Thanks< i know what You mean,  I can set the XML as a string in the out.println(xml);  I think that should help

Let me try
0
 
LVL 92

Accepted Solution

by:
objects earned 2000 total points
ID: 26134626
I see what you mean. What you would do is create a new DOM Document and add the required nodes. Then use the following to write the xml to the response

http://helpdesk.objects.com.au/java/how-to-save-a-xml-dom-document-to-a-file
0
 

Author Comment

by:AjooAli
ID: 26135752
Thanks, You suggession did help

Cheers
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Are you an Exchange administrator employed with an organization? And, have you encountered a corrupt Exchange database due to which you are not able to open its EDB file. This article will explain all the steps to repair corrupt Exchange database.
The core idea of this article is to make you acquainted with the best way in which you can export Exchange mailbox to PST format.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
Michael from AdRem Software explains how to view the most utilized and worst performing nodes in your network, by accessing the Top Charts view in NetCrunch network monitor (https://www.adremsoft.com/). Top Charts is a view in which you can set seve…
Suggested Courses
Course of the Month21 days, 5 hours left to enroll

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question