我一直在学习一个关于restful服务的教程,它运行良好。然而,有些事情我还不太明白。这就是它的样子:
@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> ";
}
}
困扰我的是我不能使用正确的操作。当我从浏览器请求服务时,会调用相应的sayHtmlHello()方法。但现在我正在开发一个android应用程序,我想在Json中得到结果。但是当我从应用程序调用服务时,会调用MediaType.TEXT_PLAIN方法。我的安卓代码看起来像这样:
使用安卓进行HTTP请求
如何从我的android应用程序中调用使用MediaType.APPLICATION_JSON的方法?此外,我想让那个特定的方法返回一个对象,如果我在那里也得到一些指导,那就太好了。
我有使用Jersey在java(JAX-RS)中实现REST的亲身经验。然后我通过一个Android应用程序连接到这个RESTful Web服务。
在您的Android应用程序中,您可以使用HTTP客户端库。它支持POST、PUT、DELETE、GET等HTTP命令。例如,使用GET命令并以JSON格式或TextPlain:传输数据
public class Client {
private String server;
public Client(String server) {
this.server = server;
}
private String getBase() {
return server;
}
public String getBaseURI(String str) {
String result = "";
try {
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpGet getRequest = new HttpGet(getBase() + str);
getRequest.addHeader("accept", "application/json");
HttpResponse response = httpClient.execute(getRequest);
result = getResult(response).toString();
httpClient.getConnectionManager().shutdown();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return result;
}
public String getBaseURIText(String str) {
String result = "";
try {
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpGet getRequest = new HttpGet(getBase() + str);
getRequest.addHeader("accept", "text/plain");
HttpResponse response = httpClient.execute(getRequest);
result = getResult(response).toString();
httpClient.getConnectionManager().shutdown();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return result;
}
private StringBuilder getResult(HttpResponse response) throws IllegalStateException, IOException {
StringBuilder result = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())), 1024);
String output;
while ((output = br.readLine()) != null)
result.append(output);
return result;
}
}
然后在安卓类中,你可以:
Client client = new Client("http://localhost:6577/Example/rest/");
String str = client.getBaseURI("Example"); // Json format
解析JSON字符串(或者可能是xml)并在ListView、GridView和。。。
我看了一下你提供的链接。有一个很好的观点。对于API 11级或更高级别,您需要在单独的线程上实现网络连接。看看这个链接:Android中的HTTP客户端API 11级或更高级别。
这是我在客户端类中发布带有HTTP的对象的方式
public String postBaseURI(String str, String strUrl) {
String result = "";
try {
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost postRequest = new HttpPost(getBase() + strUrl);
StringEntity input = new StringEntity(str);
input.setContentType("application/json");
postRequest.setEntity(input);
HttpResponse response = httpClient.execute(postRequest);
result = getResult(response).toString();
httpClient.getConnectionManager().shutdown();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return result;
}
在RESTWS中,我将对象发布到数据库:
@POST
@Path("/post")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.TEXT_PLAIN)
public Response addTask(Task task) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.save(task);
session.getTransaction().commit();
return Response.status(Response.Status.CREATED).build();
}
在上面的代码中,您评论了
// This method is called if TEXT_PLAIN is request
@GET
@Produces( MediaType.TEXT_PLAIN )...
请注意,注释@Produces
指定了OUTPUT mimetype。要指定INPUT mimetype,请改用@Consumes
注释。
查看博客文章了解更多关于泽西岛注释:
@Consumes–此注释指定资源类的方法可以接受的媒体类型。它是可选的,默认情况下,容器假设任何媒体类型都是可接受的。此注释可用于筛选客户端发送的请求。在接收到具有错误媒体类型的请求时,服务器向客户端抛出错误。
@Produces–此注释定义资源类的方法可以生成的媒体类型。与@Consumes注释一样,这也是可选的,默认情况下,容器假设任何媒体类型都可以发送回客户端。