如何在Java中使用REST

使用Java工具,

wscompile for RPC
wsimport for Document
etc..

我可以使用WSDL来生成命中SOAP Web服务所需的存根和类。

但我不知道如何在REST中做同样的事情。 我怎样才能获得碰到REST Web服务所需的Java类。 无论如何打这个服务的方式是什么?

任何人都可以告诉我方式吗?


你可以使用HttpURLConnection 。 以下是使用Java SE API(包括JAXB)调用RESTful服务的示例:

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();

你可以在这里找到完整的例子


正如其他人所说的,您可以使用较低级别的HTTP API执行此操作,也可以使用较高级别的JAXRS API将服务用作JSON。 例如:

Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://host:8080/context/rest/method");
JsonArray response = target.request(MediaType.APPLICATION_JSON).get(JsonArray.class);

只需使用正确的查询字符串或请求正文向所需的URL发送http请求即可。

例如,你可以使用java.net.HttpURLConnection ,然后通过connection.getInputStream()消耗,然后covnert到你的对象。

春天有一个restTemplate ,使它更容易一些。

链接地址: http://www.djcxy.com/p/71337.html

上一篇: How to consume REST in Java

下一篇: Why would one use REST instead of SOAP based services?