简体   繁体   中英

Restlet: sending xml in an HTTP request

How can I send xml file in an HTTP GET or HTTP put request ? I am using restlet framework. Im new to this, and according to what I've read, I should serialize the xml. After doing this, how can I send it in the HTTP request ?

It is rather simple, even if you do not use a library that combines pieces (I assume Restlet does offer some simplifications): like you mention, all you need is an HTTP connection/request, and ability to produce (and probably, consume) XML. So aside from Restlet-specific things (which hopefully others can explain), here's a "guerilla" approach, using just stand-alone pieces.

To get HTTP connection, you can just use JDK functionality (if that does not work, apache http client or async-http-client can offer more functionality); something like:

URL url = new URL("http://myservice.mycompany.com:8080/path/to/service");
// configure settings here if/as necessary
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// if you need to post stuff, do:
conn.setRequestMethod("POST");
// need to set content type too possibly
conn.setDoOutput(true); // but only if you do POST stuff
OutputStream out = conn.getOutputStream();
// here you would output XML request
//...
out.close();
// and now read response
InputStream in = conn.getInputStream();
// and process it
// ...
in.close();

now, as to producing/consume XML, you can use all the usual tools that read/write XML using input/output streams. If you like data binding (Java POJOs to/from XML), JAXB is the way to go (javax.xml.bind.*); JDK 1.6 and above bundle default implementation.

Alternatively you may simply use Stax (javax.xml.stream.*) implementation such as Woodstox , to read/write XML with simple calls; for bonus points, check out StaxMate that simplifies this style quite a bit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM