Java jersey RESTful Web 服务请求 [英] Java jersey RESTful webservice requests

查看:27
本文介绍了Java jersey RESTful Web 服务请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在关注有关宁静服务的教程,它运行良好.但是有些东西我还不太明白.看起来是这样的:

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

困扰我的是我无法使用正确的操作.当我从浏览器请求服务时,会调用相应的 sayHtmlHello() 方法.但现在我正在开发一个 android 应用程序,我想在 Json 中得到结果.但是当我从应用程序调用服务时,会调用 MediaType.TEXT_PLAIN 方法.我的 android 代码与此类似:

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:

使用 android 发出 HTTP 请求

如何从我的 android 应用程序中调用使用 MediaType.APPLICATION_JSON 的方法?此外,我想让该特定方法返回一个对象,如果我也能在那里得到一些指导,那就太好了.

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.

推荐答案

我有使用 Jersey 实现 REST in java (JAX-RS) 的个人经验.然后我通过一个 Android 应用程序连接到这个 RESTful Web 服务.

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.

在您的 Android 应用程序中,您可以使用 HTTP 客户端库.它支持 POST、PUT、DELETE、GET 等 HTTP 命令.例如使用 GET 命令并以 JSON 格式或 TextPlain 传输数据:

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:

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 类中你可以:

And then in an android class you can:

Client client = new Client("http://localhost:6577/Example/rest/");
String str = client.getBaseURI("Example");    // Json format

解析 JSON 字符串(或者可能是 xml)并在 ListView、GridView 和...中使用它

Parse the JSON string (or maybe xml) and use it in ListView, GridView and ...

我简要浏览了您提供的链接.那里有一个好点.您需要在 API 级别 11 或更高级别的单独线程上实现网络连接.查看此链接:HTTP 客户端 API 级别 11 或更高版本在 Android 中.

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.

这是我在客户端类中使用 HTTP 发布对象的方式:

This is the way that I post an object with HTTP in Client class :

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 WS 中,我将对象发布到数据库:

And in the REST WS, I post the object to the database:

    @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();
    }

这篇关于Java jersey RESTful Web 服务请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆