Reputation: 1830
I just realized that it is possible to define something like this in my RESTful resource .java file:
@GET
@Produces("text/plain")
public String getPlainTextHello() { ... }
@GET
@Produces("application/json")
public String getJSONHello() { ... }
Isn't that fantastic? But wait the moment....
PROBLEM
I am consuming my API with simple client. Something like this code with help of HttpURLConnection
:
URL obj = new URL("http://some.url/res/hello");
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
conn.setRequestMethod("GET");
... /* get response ... conn.getInputStream() */
How the server 'know' which one method call to serve the client?
Regards.
Upvotes: 0
Views: 2135
Reputation: 3065
First of all you should consider using the same method for different types of "produces":
@GET
@Produces({ "application/xml", "text/plain"})
public String getHello() { ... }
The different types of "produces" could be handled by JAXB (in case the response is an object...).
You can define the client side "accept" mime type by using:
String uri =
"http://localhost:8080/hello/";
URL url = new URL(uri);
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/json");
This question provides more insights (and other client side frameworks) related with this problem: REST. Jersey. How to programmatically choose what type to return: JSON or XML?
Upvotes: 1
Reputation: 1830
I made some more checks on this and what works for me is just settings Accept:
...
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", mime);
...
where mime
is "text/plain"
or "application/json"
. This way my server calls one of the GET function.
Anyway I am confused why most answers suggest to use a common one function to serve a @GET and check for type inside this function...
Upvotes: 0
Reputation: 9491
You'd probably want a generic function to do all the common work, and then simply pass this work to the response specific functions you outlined.
getHello(String responseType)
{
// do all your work you'd end up doing in both functions
switch (responseType):
case ("json") {
return getJSONHello(work);
}
case ("text") {
return getPlainTextHello(work);
}
}
Upvotes: 1