2012-12-23 39 views
3

我一直在尋找如何從EJB2客戶端調用Spring 3中編寫的Restful服務的示例。如果我正確理解REST,那麼寫入服務的技術/語言應該沒有關係,所以我應該能夠從EJB2客戶端調用服務。是否可以從EJB2客戶端調用Restful Web服務

我找不到一個簡單的示例或引用來指導我如何實現可以調用寧靜服務的EJB2客戶端。這是否意味着無法從EJB2客戶端調用Restful服務?如果可能的話,可否請您指出一個文檔或示例,以顯示或描述兩者如何進行對話/交談。

我遇到的大部分參考資料/文檔都與如何將EJB公開爲Web服務有關,而我對如何從EJB2調用Web服務感興趣。

我特別感興趣的是如何將XML文檔發送到服務。例如,是否可以在EJB2中使用Jersey客戶端和JAXB,以及如何使用EJB2將未編組的XML傳遞給HTTP?

在此先感謝。

+1

REST只是HTTP,所以...? – Kevin

+1

EJB2客戶端就像任何其他Java客戶端一樣,所以... –

+0

如果您可以進行http調用...您也可以調用REST服務。 –

回答

4

下面是一些用於訪問Java中的RESTful服務的程序化選項。

使用JDK/JRE的API

下面是調用使用API​​的JDK/JRE

String uri = 
    "http://localhost:8080/CustomerService/rest/customers/1"; 
URL url = new URL(uri); 
HttpURLConnection connection = 
    (HttpURLConnection) url.openConnection(); 
connection.setRequestMethod("GET"); 
connection.setRequestProperty("Accept", "application/xml"); 

JAXBContext jc = JAXBContext.newInstance(Customer.class); 
InputStream xml = connection.getInputStream(); 
Customer customer = 
    (Customer) jc.createUnmarshaller().unmarshal(xml); 

connection.disconnect(); 

RESTful服務使用新澤西州的API

大多數JAX的例子-RS實現包括使訪問RESTful服務更容易的API。客戶端API被包含在JAX-RS 2規範中。

import java.util.List; 
import javax.ws.rs.core.MediaType; 
import org.example.Customer; 
import com.sun.jersey.api.client.*; 

public class JerseyClient { 

    public static void main(String[] args) { 
     Client client = Client.create(); 
     WebResource resource = client.resource("http://localhost:8080/CustomerService/rest/customers"); 

     // Get response as String 
     String string = resource.path("1") 
      .accept(MediaType.APPLICATION_XML) 
       .get(String.class); 
     System.out.println(string); 

     // Get response as Customer 
     Customer customer = resource.path("1") 
      .accept(MediaType.APPLICATION_XML) 
       .get(Customer.class); 
     System.out.println(customer.getLastName() + ", "+ customer.getFirstName()); 

     // Get response as List<Customer> 
     List<Customer> customers = resource.path("findCustomersByCity/Any%20Town") 
      .accept(MediaType.APPLICATION_XML) 
       .get(new GenericType<List<Customer>>(){}); 
     System.out.println(customers.size()); 
    } 

} 

更多信息

+0

謝謝布萊斯。上面的例子展示瞭如何接收XML /澤西薪酬。如果可能的話,你能否以相反的方式顯示數據的一個例子。即客戶將XML/Jersey有效負載發佈到REST服務。 – ziggy