I’ve been following a tutorial about a restful service and it works fine. However there are something I dont quite understand yet. This is how it looks:
@Path("/hello")
public class Hello {
// This method is called if TEXT_PLAIN is request
@GET
@Produces( MediaType.TEXT_PLAIN )
public String sayPlainTextHello()
{
return "Plain hello!";
}
@GET
@Produces( MediaType.APPLICATION_JSON )
public String sayJsonTextHello()
{
return "Json hello!";
}
// This method is called if XML is request
@GET
@Produces(MediaType.TEXT_XML)
public String sayXMLHello() {
return "<?xml version=\"1.0\"?>" + "<hello> Hello Jersey" + "</hello>";
}
// This method is called if HTML is request
@GET
@Produces(MediaType.TEXT_HTML)
public String sayHtmlHello()
{
return "<html> " + "<title>" + "Hello fittemil" + "</title>"
+ "<body><h1>" + "Hello!" + "</body></h1>" + "</html> ";
}
}
Whats bothering me is that I can’t make use of the right operations. When I request the service from a browser the appropriate sayHtmlHello() method gets called. But now I am developing an android application which I want to get the result in Json. But when I call the service from the application, the MediaType.TEXT_PLAIN method gets called. My android code looks similar to this:
Make an HTTP request with android
How can call the method which uses MediaType.APPLICATION_JSON from my android application?
Further I would like to make that particular method return an object, would be great if I got some guidance there as well.
I have personally experience in implementing REST in java (JAX-RS) using Jersey. Then I connected to this RESTful Web Service via an Android application.
In your Android application you can use HTTP Client library. It supports the HTTP commands such as POST, PUT, DELETE, GET. For example to use GET command and trasferring data in JSON format or TextPlain:
And then in an android class you can:
Parse the JSON string (or maybe xml) and use it in ListView, GridView and …
I took a short look on the link which you had provided. There was a good point there. You need to implement your network connection on a separate thread for API level 11 or greater. Take a look on this link: HTTP Client API level 11 or greater in Android.
This is the way that I post an object with HTTP in Client class :
And in the REST WS, I post the object to the database: