Java jersey RESTful webservice requests

前端 未结 2 591
时光取名叫无心
时光取名叫无心 2021-01-14 15:17

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:

@Pa         


        
2条回答
  •  孤街浪徒
    2021-01-14 15:48

    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.

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

    And then in an android class you can:

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

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

    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.

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

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

提交回复
热议问题