1

I need to send a HTTP GET/POST request to an external API which returns XML data and then parse this data. Does an API for this exist in JSP?

If I use that code inside a class and use a method of it in JSP, will there be any problems?

1 Answer 1

2

You can use URLConnection to send a HTTP request and get the HTTP response as an InputStream. You can use JAXB to unmarshal an InputStream containing a XML document into a javabean instance which follows the XML structure.

Imagine that the XML response look like this,

<data>
    <foo>fooValue</foo>
    <bar>barValue</bar>
</data>

and your JAXB javabean look like this,

@XmlRootElement
public class Data {

    @XmlElement
    private String foo;

    @XmlElement
    private String bar;

    // Getters/setters.
}

then you can unmarshal it something like as follows:

InputStream input = new URL("http://example.com/data.xml").openStream();
Data data = (Data) JAXBContext.newInstance(Data.class).createUnmarshaller().unmarshal(input);
String foo = data.getFoo(); // fooValue
// ...

As with every other line of Java code in JSP, doing this in a JSP file instead of a normal Java class doesn't necessarily cause technical problems, but it may end up in maintenance nightmare.

Sign up to request clarification or add additional context in comments.

13 Comments

thanku. After that how to access a particular element ? data contains unmarshalled content. How to access "username" element form it ?
Uh, just add a normal javabean getter method to the Data class as in the example. Are you familiar with javabeans? Have you bothered to click the JAXB link? It points you to the JAXB tutorial.
i am newbie. I have checked that manual. But it was hard to understand. So to avoid confusingmyself, i am trying to find a simple and easy to understand tutorial. I do not know much about java bean. Is it creating a class with a property name which is same as the XML element and writing a function to return that variable, that you are talking about ?
thanku for the example. JAXB javabean is same as a class. Correct ?
Uh, that's just a Java class, yes. I'd suggest to put this all aside and take some days/weeks to go through a basic Java book/tutorial first to familiarize yourself with the basics of the Java language and terminology.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.