Java 如何使用RESTful web服务?
在 教程编写了如何创建REST服务以及如何使用它。我被这个例子弄糊涂了。我们需要在客户端使用jersey.jar,并这样编写:Java 如何使用RESTful web服务?,java,web-services,rest,Java,Web Services,Rest,在 教程编写了如何创建REST服务以及如何使用它。我被这个例子弄糊涂了。我们需要在客户端使用jersey.jar,并这样编写: Client client = Client.create(config); WebResource service = client.resource(getBaseURI()); 为什么客户端需要知道web服务是如何实现的(jersey或可能是ohter实现)?为什么客户端不使用simpleInputStream?在本教程中,您将使用jersey客户端与RESTf
Client client = Client.create(config);
WebResource service = client.resource(getBaseURI());
为什么客户端需要知道web服务是如何实现的(jersey或可能是ohter实现)?为什么客户端不使用simple
InputStream
?在本教程中,您将使用jersey客户端与RESTful服务交互
您也可以直接与服务交互,只需手动创建HTTP请求并接收相应的响应和解析(http://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html).
Jersey客户端最终只是一个抽象,使其更易于使用。使用Restful web服务的最简单方法是使用Spring RestTemplate。
String URL ="http://localhost:8080/MyWServices/REST/WebService/";
String ws_method_name = "getManagerListByRoleID";
String WS_METHOD_PARAMS = "";
HttpClient httpClient = new DefaultHttpClient();
HttpContext httpContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(URL + ws_method_name + WS_METHOD_PARAMS);
String text = null;
try {
HttpResponse httpResponse = httpClient
.execute(httpGet, httpContext);
HttpEntity entity = httpResponse.getEntity();
text = getASCIIContentFromEntity(entity);
}catch(Exception e){
e.printStackTrace();
}
如同一教程中所述,“Jersey包含一个REST客户端库,可用于测试或用Java构建真正的客户端。或者,您可以使用Apache HttpClient创建客户端。”