在Java中调用REST API
如果您正在开发一个允许您连接服务器的程序,您可能会熟悉 REST API。 通过这个API,您可以连接到特定的服务器。
在本文中,我们将了解 REST API、它的工作原理和关键功能,以及如何使用 GET 和 POST 请求在 Java 中调用 REST API。
Java REST API 概述
REST 一词被定义为表述性状态转移。 它是如何工作的? 在这个系统中,您的程序是一个客户端,可以向服务器发送请求以获取一些数据。
另一方面,这里的服务器接收该调用并响应客户端。 该请求和响应对遵循称为 HTTP 或超文本传输协议的协议。
REST API 的主要特性
以下是 REST API 的主要功能:
- REST API 的设计是无状态的,这意味着当客户端和服务器想要连接时,它们将需要一条额外的信息来完成请求。
- REST API 还可以缓存资源以获得更好的性能。
- REST API 使用统一的接口,使客户端能够以特定语言与服务器对话。
在 Java 中使用 GET 和 POST 请求调用 REST API
GET 接收指定资源的表示,而 POST 用于将要处理的数据写入已识别的资源。 下面我们来学习如何使用它们来调用 REST API。
使用 GET 请求
示例代码:
// Importing all the necessary packages
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HTTPGet {
public static void main(String args[]) throws Exception {
// Providing the website URL
URL url = new URL("http://example.com");
// Creating an HTTP connection
HttpURLConnection MyConn = (HttpURLConnection) url.openConnection();
// Set the request method to "GET"
MyConn.setRequestMethod("GET");
// Collect the response code
int responseCode = MyConn.getResponseCode();
System.out.println("GET Response Code :: " + responseCode);
if (responseCode == MyConn.HTTP_OK) {
// Create a reader with the input stream reader.
BufferedReader in = new BufferedReader(new InputStreamReader(
MyConn.getInputStream()));
String inputLine;
// Create a string buffer
StringBuffer response = new StringBuffer();
// Write each of the input line
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//Show the output
System.out.println(response.toString());
} else {
System.out.println("Error found !!!");
}
}
}
在上面的示例中,我们演示了 HTTP 中最常用的请求方法,即 GET。 我们已经在示例代码中写下了每一行的用途。
在此示例中,我们根据提供的 URL 创建了一个 HTTP 连接,然后定义了请求的属性。 之后,我们将请求方法设置为GET。
然后我们用InputStreamReader创建了一个BufferedReader来读取并保存每个文档行。 最后,我们将网站打印为输出。
输出:
GET Response Code :: 200
<!doctype html>
<html>
<head>
<title>Example Domain</title>
<meta charset="utf-8">
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style type="text/css">
body {
background-color: #f0f0f2;
margin: 0;
padding: 0;
font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
}
div {
width: 600px;
margin: 5em auto;
padding: 2em;
background-color: #fdfdff;
border-radius: 0.5em;
box-shadow: 2px 3px 7px 2px rgba(0,0,0,0.02);
}
a:link, a:visited {
color: #38488f;
text-decoration: none;
}
@media (max-width: 700px) {
div {
margin: 0 auto;
width: auto;
}
}
</style>
</head>
<body>
<div>
<h1>Example Domain</h1>
<p>This domain is for use in illustrative examples in documents. You may use this domain in literature without prior coordination or asking for permission.</p>
<p><a href="https://www.iana.org/domains/example">More information...</a></p>
</div>
</body>
</html>
使用 POST 请求
示例代码:
// Importing all the necessary packages
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class HTTPPost {
public static void main(String[] args) throws MalformedURLException, IOException {
// Providing the website URL
URL myUrl = new URL("https://example.com");
// Creating an HTTP connection
HttpURLConnection MyConn = (HttpURLConnection) myUrl.openConnection();
// Set the request method to "POST"
MyConn.setRequestMethod("POST");
MyConn.setDoOutput(true);
// Creating an output stream
OutputStream out = MyConn.getOutputStream();
// Defining the sting to post
String postedString = "This is the posted text !!!!!!";
out.write(postedString.getBytes());
// Collect the response code
int responseCode = MyConn.getResponseCode();
System.out.print("Value of http created is:" + MyConn.HTTP_CREATED + "\n");
if (responseCode == MyConn.HTTP_CREATED) {
System.out.print("This is the response Code: " + responseCode + "\n");
System.out.print("This is the response Message fromserver: "
+ MyConn.getResponseMessage() + "\n");
} else {
System.out.print("GO HOME, EVERYBODY :( ");
}
// Creating an input stream reader
InputStreamReader in = new InputStreamReader(MyConn.getInputStream());
// Creating a buffered reader
BufferedReader buffer = new BufferedReader(in);
// Creating a string buffer
StringBuffer fromServer = new StringBuffer();
String eachLine = null;
// Writing each line of the document
while ((eachLine = buffer.readLine()) != null) {
fromServer.append(eachLine);
fromServer.append(System.lineSeparator());
}
buffer.close();
// Printing the html document
System.out.print("Here is our webpage:\n" + fromServer);
}
}
输出:
Value of http created is:201
GO HOME, EVERYBODY :( Here is our webpage:
<!doctype html>
<html>
<head>
<title>Example Domain</title>
<meta charset="utf-8">
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style type="text/css">
body {
background-color: #f0f0f2;
margin: 0;
padding: 0;
font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
}
div {
width: 600px;
margin: 5em auto;
padding: 2em;
background-color: #fdfdff;
border-radius: 0.5em;
box-shadow: 2px 3px 7px 2px rgba(0,0,0,0.02);
}
a:link, a:visited {
color: #38488f;
text-decoration: none;
}
@media (max-width: 700px) {
div {
margin: 0 auto;
width: auto;
}
}
</style>
</head>
<body>
<div>
<h1>Example Domain</h1>
<p>This domain is for use in illustrative examples in documents. You may use this domain in literature without prior coordination or asking for permission.</p>
<p><a href="https://www.iana.org/domains/example">More information...</a></p>
</div>
</body>
</html>
在上面的示例中,我们演示了 HTTP 中另一种最常用的请求方法,即 POST。 在示例中,我们根据提供的 URL 创建了一个 HTTP 连接,然后定义了请求的属性。
之后,我们将请求方法设置为POST。 然后,我们设置一个OutputStream来发送字符串; 之后,我们处理响应代码。
接下来,我们使用 InputStreamReader 创建了一个 BufferedReader。 然后我们创建了一个 StringBuffer 来保存所有文档。 希望您已经学会了如何在 Java 中使用 GET/POST 请求调用 REST API。
相关文章
如何在 Java 中延迟几秒钟的时间
发布时间:2023/12/17 浏览次数:217 分类:Java
-
本篇文章主要介绍如何在 Java 中制造程序延迟。本教程介绍了如何在 Java 中制造程序延时,并列举了一些示例代码来了解它。
如何在 Java 中把 Hashmap 转换为 JSON 对象
发布时间:2023/12/17 浏览次数:187 分类:Java
-
它描述了允许我们将哈希图转换为简单的 JSON 对象的方法。本文介绍了在 Java 中把 Hashmap 转换为 JSON 对象的方法。我们将看到关于创建一个 hashmap,然后将其转换为 JSON 对象的详细例子。
如何在 Java 中按值排序 Map
发布时间:2023/12/17 浏览次数:171 分类:Java
-
本文介绍了如何在 Java 中按值对 Map 进行排序。本教程介绍了如何在 Java 中按值对 Map
进行排序,并列出了一些示例代码来理解它。
如何在 Java 中打印 HashMap
发布时间:2023/12/17 浏览次数:192 分类:Java
-
本帖介绍了如何在 Java 中打印 HashMap。本教程介绍了如何在 Java 中打印 HashMap 元素,还列举了一些示例代码来理解这个主题。
在 Java 中更新 Hashmap 的值
发布时间:2023/12/17 浏览次数:146 分类:Java
-
本文介绍了如何在 Java 中更新 HashMap 中的一个值。本文介绍了如何在 Java 中使用 HashMap 类中包含的两个方法-put() 和 replace() 更新 HashMap 中的值。
Java 中的 hashmap 和 map 之间的区别
发布时间:2023/12/17 浏览次数:79 分类:Java
-
本文介绍了 Java 中的 hashmap 和 map 接口之间的区别。本教程介绍了 Java 中 Map 和 HashMap 之间的主要区别。在 Java 中,Map 是用于以键值对存储数据的接口,
在 Java 中获取用户主目录
发布时间:2023/12/17 浏览次数:218 分类:Java
-
这篇文章向你展示了如何在 Java 中获取用户主目录。本教程介绍了如何在 Java 中获取用户主目录,并列出了一些示例代码以指导你完成该主题。
Java 中 size 和 length 的区别
发布时间:2023/12/17 浏览次数:179 分类:Java
-
这篇文章教你如何知道 Java 中大小和长度之间的区别。本教程介绍了 Java 中大小和长度之间的区别。我们还列出了一些示例代码以帮助你理解该主题。
Java 中的互斥锁
发布时间:2023/12/17 浏览次数:111 分类:Java
-
了解有关 Java 中互斥锁的一切,在计算机科学领域,互斥或互斥被称为并发控制的属性。每台计算机都使用称为线程的最小程序指令序列。有一次,计算机在一个线程上工作。为了更好地理解,