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

以下是用于使用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.客户端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

List customers = resource.path("findCustomersByCity/Any%20Town")

.accept(MediaType.APPLICATION_XML)

.get(new GenericType>(){});

System.out.println(customers.size());

}

}

欲获得更多信息

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值