从Seam调用Web服务
时间:2020-03-05 18:51:34 来源:igfitidea点击:
这是一个简单的问题,但是有人可以提供示例代码,说明有人如何在JBoss Seam框架内调用Web服务并处理结果吗?
我需要能够与由私人供应商提供的搜索平台集成,该供应商将其功能公开为Web服务。因此,我只是在寻找有关调用给定Web服务的代码的外观的指导。
(可以选择任何示例Web服务作为示例。)
解决方案
回答
import org.restlet.Client; import org.restlet.data.Protocol; import org.restlet.data.Reference; import org.restlet.data.Response; import org.restlet.resource.DomRepresentation; import org.w3c.dom.Node; /** * Uses YAHOO!'s RESTful web service with XML. */ public class YahooSearch { private static final String BASE_URI = "http://api.search.yahoo.com/WebSearchService/V1/webSearch"; public static void main(final String[] args) { if (1 != args.length) { System.err.println("You need to pass a search term!"); } else { final String term = Reference.encode(args[0]); final String uri = BASE_URI + "?appid=restbook&query=" + term; final Response response = new Client(Protocol.HTTP).get(uri); final DomRepresentation document = response.getEntityAsDom(); document.setNamespaceAware(true); document.putNamespace("y", "urn:yahoo:srch"); final String expr = "/y:ResultSet/y:Result/y:Title/text()"; for (final Node node : document.getNodes(expr)) { System.out.println(node.getTextContent()); } } } }
此代码使用Restlet向Yahoo的RESTful搜索服务发出请求。显然,我们所使用的Web服务的详细信息将决定客户端的外观。
回答
final Response response = new Client(Protocol.HTTP).get(uri);
因此,如果我正确理解这一点,则在上面的行是对Web服务的实际调用,将响应转换为适当的格式并在此行之后进行操作。
假设我没有使用Restlet,这行会有什么不同?
(当然,实际的处理代码也将有很大的不同,所以这是给定的。)
回答
大约有数以百万计的HTTP客户端库(Restlet远远不止于此,但我已经有了用于其他功能的代码段),但是它们都应提供发送GET请求的支持。这是一个使用Apache Commons的HttpClient的功能较少的代码段:
HttpClient client = new HttpClient(); HttpMethod method = new GetMethod("http://api.search.yahoo.com/WebSearchService/V1/webSearch?appid=restbook&query=HttpClient"); client.executeMethod(method);