I am developing an Dynamic Web Application with Eclipse. I have e working MySQL-Database which is connected over a class called 'Data Access Object' (=DAO) that works with JDBC. I want to create entries into this database. The functions are ready. With ready I mean tested and OK. On the same application I implemented Java Jersey's RESTful WebService. It is working well, I can call the service and it returns my desired information. But now to my question:
How can I send a String containing XML? The String has to be parsed in the WebMethod to build and execute the query.
My WebService looks as follows:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.ws.rs.Consumes;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
@Path("/input")
public class Input {
//DAO instance to have connection to the database.
//Not used yet.
//private DAO dao = new DAO();
@PUT
@Consumes(MediaType.TEXT_XML)
@Path("/result")
public void putIntoDAO(InputStream xml) {
String line = "";
StringBuilder sb = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(xml));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(sb.toString());
}
}
As you see I tried to print the incoming Stream to the console. I repeat the most important things:
What I would like to know:
Thank you for your attention and try to help me. I appreciate even every try to.
Kind regards
L.
How do I access this String in my PUT-method?
You can simply code the method to take an argument of type String
and Jersey will map this from the incoming XML request, so:
@PUT
@Consumes(MediaType.TEXT_XML)
@Path("/result")
public void putIntoDAO(String xml) {
// ...
}
Should work, with the String containing the full request body.
How do I send an XML-String to my WebService?
This depends on what you're using to send the request to the service, which could be anything which communicates over HTTP. I'll assume you're using Java and sticking with Jersey, so one option is you can use the Jersey Client in the following way:
Client client = Client.create();
WebResource webResource = client.resource("http://localhost:8080/input/result");
String input = "<xml></xml>";
ClientResponse response = webResource
.type("application/xml")
.put(ClientResponse.class, input);
See the Jersey Client documentation for more.