Java的球衣RESTful Web服务请求 [英] Java jersey restful webservice requests

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

问题描述

我一直在关注有关RESTful服务的教程,它工作正常。然而,有一些东西我不很明白呢。这是它的外观:

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()方法被调用。但现在我发展,我希望得到的结果以JSON一个Android应用程序。但是,当我我调用该服务的应用程序中,MediaType.TEXT_PLAIN方法被调用。我的Andr​​oid code类似于此:

Whats bothering me is that I can't make use of the right operations. When i request the service from a browser the appropiate sayHtmlHello() method gets called. But now I am developing a android application which i want to get the result in Json. But when I i call the service from the application, the MediaType.TEXT_PLAIN method gets called. My android code looks similar to this:

请与Android 的HTTP请求

如何可以调用它采用MediaType.APPLICATION_JSON从我的Andr​​oid应用程序的方法是什么? 另外我想提出的特定方法返回一个对象,将是巨大的,如果我得到了一些指导那里。

How can call the method which uses MediaType.APPLICATION_JSON from my android application? Further I would like to make that particular method return a object, would be great if i got some guidance there as well.

推荐答案

我在执行使用REST新泽西州的爪哇(JAX-RS)亲自体验一下。然后,我通过一个Android应用程序连接到这个基于REST的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.

在你的Andr​​oid应用程序,你可以使用HTTP客户端库。它支持HTTP命令,例如POST,PUT,DELETE,GET。例如使用GET JSON格式或TextPlain指挥trasferring数据:

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或更高版本上的一个单独的线程您的网络连接。就拿这个链接一看:<一href="http://stackoverflow.com/questions/10904225/http-client-api-level-11-or-greater-in-android">HTTP客户端API 11级或更大的Andr​​oid 。

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的球衣RESTful Web服务请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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