如何在Servlet内调用Java Rest WebService

6

我有一个Java Restful WebService的URL: http://localhost:8080/WebServiceEx/rest/hello/dgdg

当我执行这个URL时,WebService方法会返回一个字符串。

我的需求是在Servlet中调用上述的WebService URL,有谁能帮忙吗?

Servlet代码:

public Class StoreServlet extends HttpServlet{
 protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws IOException, ServletException {

//Invoke WebService and Get Response String Here


} 

WebService 代码:

public class HelloWorldService {
    @Context 
    private ServletContext context;

    @GET
    @Path("/{param}")
    public Response getMsg(@PathParam("param") String msg) {

                    return Response.status(200).entity(msg).build();    

                }
    }
2个回答

4

看看Apache CXF JAX-RS客户端:

http://cxf.apache.org/docs/jax-rs-client-api.html

例如

BookStore store = JAXRSClientFactory.create("http://bookstore.com", BookStore.class);
// (1) remote GET call to http://bookstore.com/bookstore
Books books = store.getAllBooks();
// (2) no remote call
BookResource subresource = store.getBookSubresource(1);
// {3} remote GET call to http://bookstore.com/bookstore/1
Book b = subresource.getBook();

如果你使用 JAX-RS 2.0,它有一个客户端 API

例如:

Client client = ClientFactory.newClient();

String bal = client.target("http://.../atm/balance")
                   .queryParam("card", "111122223333")
                   .queryParam("pin", "9876")
                   .request("text/plain").get(String.class); 

或者您可以使用纯Java的“核心”方式进行操作:http://www.mkyong.com/webservices/jax-rs/restfull-java-client-with-java-net-url/


0
一种可能性是使用jaxws生成webservice客户端(为此目的-在互联网上查找教程)。这样,您就可以获得一些Java类,可以像通常在servlet中一样使用它们。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接