Java Jersey RESTful Web服务请求

3

我一直在跟踪一篇关于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方法被调用。我的Android代码类似于以下内容:在Android中进行HTTP请求
我该如何调用使用MediaType.APPLICATION_JSON的方法?此外,我还想让特定的方法返回一个对象,如果能给予一些指导将会很好。
2个回答

4
我个人有在Java(JAX-RS)中实现REST并使用Jersey的经验。然后我通过Android应用程序连接到这个RESTful Web服务。
在您的Android应用程序中,您可以使用HTTP Client库。它支持HTTP命令,例如POST、PUT、DELETE、GET。例如,要使用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;      
      }
}

然后在 Android 类中,您可以:

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;
    }

在REST Web服务中,我将对象提交到数据库:
    @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();
    }

感谢您的贡献!特别是addHeader部分正是我所寻找的,之前不知道有这个功能。 - Lucas Arrefelt

1
在上面的代码中,您进行了注释。
// This method is called if TEXT_PLAIN is request
@GET
@Produces( MediaType.TEXT_PLAIN )...

请注意注释@Produces指定了输出的MIME类型。要指定输入的MIME类型,请改用@Consumes注释。

有关Jersey注释的更多信息,请查看博客文章

@Consumes - 此注释指定资源类的方法可以接受的媒体类型。它是可选的,容器默认情况下认为任何媒体类型都是可接受的。此注释可用于过滤客户端发送的请求。如果收到错误的媒体类型请求,则服务器向客户端抛出错误。

@Produces - 此注释定义了资源类的方法可以生成的媒体类型。与@Consumes注释类似,这也是可选的,默认情况下,容器会假设可以将任何媒体类型发送回客户端。


不客气!如果您认为这是您问题的正确答案,请检查一下V符号 :) - Giorgio
我确定你是指 @Consumes 注解而不是 @Accept 注解。 - Japheth Ongeri - inkalimeva

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接