How to make restful calls from server?
Hi i have a restful project and I make rest calls from client side. But for a case I need to make restful calls from server side. How can i do that?开发者_如何学编程
You can use Apache HttpClient library for this.
As mentioned by @Jonas use HttpClient. Actually there is no difference between client and server in this case. Your server is a client of another server.
But be careful:
if you are in Java EE environment you are not expected to open sockets yourself (at least from EJB). The "right" solution is using JCA to connect to other systems. I once implemented JCA adapter: it is not so hard but requires some efforts.
Probably easier solution is to put the code that opens sockets into servlet, e.g. one servlet turns to another one (running on different server) over HTTP. I think it is not strongly forbidden by Java EE spec.
The JAX/RS client libraries may be used in server code.
My blog has more detail, but here's the relevant code. I'm using Apache Wink.
Resource editionResource = libraryClient.resource(
"http://localhost:9085/LibraryWink/library/editions”
);
BookEdition theEdition = new BookEdition(
/* title, isbn etc */
);
ClientResponse response = editionResource
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.post(theEdition);
精彩评论