gpt4 book ai didi

java - 如何在 Servlet 中调用 java Rest WebService

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:21:52 25 4
gpt4 key购买 nike

我有一个 java Rest 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


}

网络服务代码:

public class HelloWorldService {
@Context
private ServletContext context;

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

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

}
}

最佳答案

看看 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,它有一个 client 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/

关于java - 如何在 Servlet 中调用 java Rest WebService,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17296818/

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