2011-08-21 54 views
3

我正在開發一個需要通過CXF Web服務連接到遠程數據庫的Android應用程序。我嘗試過使用Soap,但由於各種問題而遺留了該選項,並選擇了基於輕量級REST的服務(通過添加註釋到現有的cxf網絡服務)。我有一個從活動內部調用的Rest客戶端。 我使用了像String,int等簡單參數。現在我想將用戶定義的對象 傳遞給服務,並從服務器端獲取一些字符串值。我該如何做? 請幫助...在谷歌搜索我找到關於使用JSON,JAXB等文章,但我不知道這些做什麼或如何使用這些。我對使用這些技術編程非常陌生。如何使用CXF REST客戶端傳遞用戶定義的對象?

回答

2

你可以做你的客戶端代碼類似:

private static final String URI = "http://localhost/rest/customer"; 

private Customer readCustomer(String id) { 
    try { 
     URL url = new URL(URI + "/" + id); 
     HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
     connection.setRequestMethod("GET"); 
     connection.setRequestProperty("Accept", "application/xml"); 

     InputStream data = connection.getInputStream(); 
     // TODO - Read data from InputStream 

     connection.disconnect(); 
     return customer; 
    } catch(Exception e) { 
     throw new RuntimeException(e); 
    } 
} 

private void createCustomer(Customer customer) { 
    try { 
     URL url = new URL(URI); 
     HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
     connection.setDoOutput(true); 
     connection.setInstanceFollowRedirects(false); 
     connection.setRequestMethod("POST"); 
     connection.setRequestProperty("Content-Type", "application/xml"); 

     OutputStream os = connection.getOutputStream(); 
     // TODO - Write data to OutputStream 
     os.flush(); 

     connection.getResponseCode(); 
     connection.disconnect(); 
    } catch(Exception e) { 
     throw new RuntimeException(e); 
    } 
} 

private void updateCustomer(Customer customer) { 
    try { 
     URL url = new URL(URI); 
     HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
     connection.setDoOutput(true); 
     connection.setInstanceFollowRedirects(false); 
     connection.setRequestMethod("PUT"); 
     connection.setRequestProperty("Content-Type", "application/xml"); 

     OutputStream os = connection.getOutputStream(); 
     // TODO - Write data to OutputStream 
     os.flush(); 

     connection.getResponseCode(); 
     connection.disconnect(); 
    } catch(Exception e) { 
     throw new RuntimeException(e); 
    } 
} 

private void deleteCustomer(String id) { 
    try { 
     URL url = new URL(URI + "/" + id); 
     HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
     connection.setRequestMethod("DELETE"); 
     connection.getResponseCode(); 
     connection.disconnect(); 
    } catch(Exception e) { 
     throw new RuntimeException(e); 
    } 
} 
相關問題