【问题标题】:Is it possible to call a Restful web service from an EJB2 client是否可以从 EJB2 客户端调用 Restful Web 服务
【发布时间】:2012-12-23 17:03:28
【问题描述】:

我一直在寻找如何从 EJB2 客户端调用用 Spring 3 编写的 Restful 服务的示例。如果我正确理解 REST,那么服务是用什么技术/语言编写的都无关紧要,因此我应该能够从 EJB2 客户端调用该服务。

我找不到一个简单的示例或参考来指导我如何实现一个可以调用 RESTful 服务的 EJB2 客户端。这是否意味着无法从 EJB2 客户端调用 Restful 服务?如果可能的话,能否请您指向一个文档或示例,以显示或描述两者如何相互交流/交谈。

我遇到的大多数参考/文档都与如何将 EJB 公开为 Web 服务有关,而我对如何从 EJB2 调用 Web 服务感兴趣。

我对如何将 XML 文档发送到服务特别感兴趣。例如,是否可以将 Jersey 客户端和 JAXB 与 EJB2 一起使用,我将如何使用 EJB2 通过 HTTP 传递未编组的 XML?

提前致谢。

【问题讨论】:

  • EJB2 客户端就像任何其他 Java 客户端一样,所以...
  • 如果你可以进行http调用...你也可以调用REST服务。
  • 我知道我可以通过 HTTP 调用来调用 Rest 服务。是否可以在 EJB 2 中使用带有 JAXB 的 Jersey 客户端来调用 REST 服务?
  • @ziggy:为什么不可能?

标签: java web-services spring rest ejb


【解决方案1】:

以下是在 Java 中访问 RESTful 服务的几个编程选项。

使用 JDK/JRE API

以下是使用 JDK/JRE 中的 API 调用 RESTful 服务的示例

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

使用 Jersey API

大多数 JAX-RS 实现都包含使访问 RESTful 服务更容易的 API。 JAX-RS 2 规范中包含了一个客户端 API。

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

}

更多信息

【讨论】:

  • 谢谢布莱斯。上面的例子展示了如何接收一个 XML/Jersey paylod。如果可能的话,您能否展示一个以其他方式输出的数据示例。即客户端将 XML/Jersey 有效负载发布到 REST 服务。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-04
  • 1970-01-01
  • 1970-01-01
  • 2013-08-22
  • 1970-01-01
  • 1970-01-01
  • 2011-12-06
相关资源
最近更新 更多