要使用JDK的Java RESTful Web服务库,您可以使用Java内置的HttpURLConnection类来发送HTTP请求,并使用Jackson库来处理JSON数据。以下是一个简单的示例代码:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.3</version>
</dependency>
URL url = new URL("http://example.com/api/data");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 读取响应数据
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuffer response = new StringBuffer();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// 处理响应数据
ObjectMapper objectMapper = new ObjectMapper();
YourDataClass data = objectMapper.readValue(response.toString(), YourDataClass.class);
}
connection.disconnect();
URL url = new URL("http://example.com/api/data");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
String postData = "{ \"key\": \"value\" }";
OutputStream os = connection.getOutputStream();
os.write(postData.getBytes());
os.flush();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 处理响应数据
}
connection.disconnect();
通过使用HttpURLConnection类和Jackson库,您可以轻松地创建和发送RESTful Web服务请求,并处理响应数据。请记得处理异常和关闭连接以确保代码的健壮性。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。