How to consume REST in Java
Using Java tools,
wscompile for RPC
wsimport for Document
etc..
I can use WSDL to generate the stub and Classes required to hit the SOAP Web Service.
But I have no idea how I can do the same in REST. How can I get the Java classes required for hitting the REST Web Service. What is the way to hit the service anyway?
Can anyone show me the way?
You can use HttpURLConnection
. Below is an example of calling a RESTful service using the Java SE APIs including JAXB:
String uri =
"http://localhost:8080/CustomerService/rest/customers/1";
URL url = new URL(uri);
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/xml");
JAXBContext jc = JAXBContext.newInstance(Customer.class);
InputStream xml = connection.getInputStream();
Customer customer =
(Customer) jc.createUnmarshaller().unmarshal(xml);
connection.disconnect();
You can find the complete example here
As others have said, you can do it using the lower level HTTP API, or you can use the higher level JAXRS APIs to consume a service as JSON. For example:
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://host:8080/context/rest/method");
JsonArray response = target.request(MediaType.APPLICATION_JSON).get(JsonArray.class);
Just make an http request to the required URL with correct query string, or request body.
For example you could use java.net.HttpURLConnection
and then consume via connection.getInputStream()
, and then covnert to your objects.
In spring there is a restTemplate
that makes it all a bit easier.
上一篇: 保护应用程序的休息API
下一篇: 如何在Java中使用REST