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