2012-07-13 29 views
3

我一直在關注一個關於寧靜服務的教程,它工作正常。不過,有些東西我還不太明白。這是它的外觀:Java平臺REST風格的web服務請求

@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

如何可以調用它使用MediaType.APPLICATION_JSON從我的Android應用程序的方法是什麼? 此外,我想使特定的方法返回一個對象,如果我也有一些指導,那將是非常好的。

回答

4

我個人有經驗在使用Jersey實現REST的Java(JAX-RS)中。然後,我通過Android應用程序連接到這個RESTful Web服務。

在您的Android應用程序中,您可以使用HTTP客戶端庫。它支持HTTP命令,例如POST,PUT,DELETE,GET。例如使用GET JSON格式或TextPlain命令和trasferring數據:

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

,然後在機器人類,你可以:

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

感謝您的輸入!特別是addHeader部分是我正在尋找的,不知道那個 – 2012-07-15 12:53:00

1

在代碼以上你評論過

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

請注意,註釋@Produces指定了OUTPUT mimetype。 要指定INPUT mimetype,請改用@Consumes註釋。

檢查blog post更多有關新澤西註釋:

@Consumes - 此批註指定介質類型的資源類的方法可以接受。它是可選的,默認情況下,容器假定任何媒體類型都可以接受。此註釋可用於過濾客戶端發送的請求。在接收到錯誤媒體類型的請求時,服務器向客戶端拋出錯誤。

@Produces - 這個註解定義了資源類的方法可以產生的媒體類型。像@Consumes註釋一樣,這也是可選的,默認情況下,容器假設任何媒體類型都可以發送回客戶端。

+0

感謝您的清晰! – 2012-07-15 12:53:19

+0

不客氣!請檢查V符號,如果你認爲這是你的問題的正確答案:) – Giorgio 2012-07-15 19:04:19

+0

我相信你的意思是「@ Consumes」註釋而不是'@ Accept'註釋 – 2016-08-29 05:48:27