【问题标题】:Java jersey RESTful webservice requestsJava jersey RESTful Web 服务请求
【发布时间】:2012-07-13 23:50:57
【问题描述】:

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

@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 代码与此类似:

Make an HTTP request with android

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

【问题讨论】:

    标签: android json web-services jersey


    【解决方案1】:

    我有使用 Jersey 实现 REST in java (JAX-RS) 的个人经验。然后我通过一个 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;      
          }
    }
    

    然后在一个 android 类中你可以:

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

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

    我简要浏览了您提供的链接。那里有一个好点。您需要在 API 级别 11 或更高级别的单独线程上实现网络连接。看看这个链接:HTTP Client API level 11 or greater in Android

    这是我在客户端类中使用 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 WS 中,我将对象发布到数据库:

        @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 部分是我正在寻找的,不知道
    【解决方案2】:

    在上面你注释的代码中

    // This method is called if TEXT_PLAIN is request
    @GET
    @Produces( MediaType.TEXT_PLAIN )...
    

    请注意注解@Produces 指定了OUTPUT mimetype。 要指定 INPUT mimetype,请改用 @Consumes 注释。

    查看blog post 了解更多关于 Jersey 注释的信息:

    @Consumes – 此注释指定资源类的方法可以接受的媒体类型。这是一个可选的,默认情况下,容器假定任何媒体类型都是可接受的。该注解可用于过滤客户端发送的请求。在接收到错误媒体类型的请求时,服务器会向客户端抛出错误。

    @Produces——这个注解定义了资源类的方法可以产生的媒体类型。与@Consumes 注解一样,这也是可选的,默认情况下,容器假定可以将任何媒体类型发送回客户端。

    【讨论】:

    • 不客气!如果您认为这是您问题的正确答案,请检查 V 符号 :)
    • 我确定您的意思是 @Consumes 注释而不是 @Accept 注释
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-17
    • 2014-09-13
    • 2017-05-24
    • 1970-01-01
    • 2015-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多