如何在 Java 中使用 REST [英] How to consume REST in Java
本文介绍了如何在 Java 中使用 REST的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用 Java 工具,
Using Java tools,
wscompile for RPC
wsimport for Document
etc..
我可以使用 WSDL 生成命中 SOAP Web 服务所需的存根和类.
I can use WSDL to generate the stub and Classes required to hit the SOAP Web Service.
但我不知道如何在 REST 中做同样的事情.如何获取访问 REST Web 服务所需的 Java 类.无论如何打服务的方法是什么?
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?
谁能给我指路?
推荐答案
工作示例,试试这个:
package restclient;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class NetClientGet {
public static void main(String[] args) {
try {
URL url = new URL("http://localhost:3002/RestWebserviceDemo/rest/json/product/dynamicData?size=5");//your url i.e fetch data from .
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP Error code : "
+ conn.getResponseCode());
}
InputStreamReader in = new InputStreamReader(conn.getInputStream());
BufferedReader br = new BufferedReader(in);
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (Exception e) {
System.out.println("Exception in NetClientGet:- " + e);
}
}
}
这篇关于如何在 Java 中使用 REST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文