gpt4 book ai didi

java - 是否可以从 EJB2 客户端调用 Restful Web 服务

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:19:48 26 4
gpt4 key购买 nike

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

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

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

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

提前致谢。

最佳答案

下面是一些用于访问 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());
}

}

了解更多信息

关于java - 是否可以从 EJB2 客户端调用 Restful Web 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14012857/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com