使用curl測試REST API

REST
Remote
1
08:56 AM · Dec 01 ,2025

1. 概述

本教程提供了一個簡要的概述,介紹了使用 curl 測試 REST API 的方法。

curl 是一個命令行工具,用於傳輸數據,並支持約 22 種協議,包括 HTTP。 這使得它成為測試我們 REST 服務的一個非常好的臨時工具。

2. 命令行選項

curl 支持超過 200 個命令行的選項。我們可以有零個或多個選項來伴隨命令中的 URL。

在使用它來滿足我們的需求之前,讓我們先查看兩個可以使我們的生活更輕鬆的選項。

2.1. Verbose

當我們進行測試時,設置 Verbose 模式是一個好主意:

curl -v http://www.example.com/

結果,命令提供了有用的信息,例如解析的 IP 地址、我們嘗試連接到的端口以及標頭。

2.2. Output

默認情況下,curl 將響應體輸出到標準輸出。 此外,我們還可以提供輸出選項以將輸出保存到文件:

curl -o out.json http://www.example.com/index.html

這在響應大小為大小時尤其有用。

3. HTTP Methods With curl

Every HTTP request contains a method. The most commonly used methods are GET, POST, PUT and DELETE.

3.1. GET

This is the default method when making HTTP calls with curl. In fact, the examples previously shown were plain GET calls.

While running a local instance of a service at port 8082, we’d use something like this command to make a GET call:

curl -v http://localhost:8082/spring-rest/foos/9

Since we have the verbose mode on, we get a little more information along with the response body:

*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8082 (#0)
> GET /spring-rest/foos/9 HTTP/1.1
> Host: localhost:8082
> User-Agent: curl/7.60.0
> Accept: */*
>
< HTTP/1.1 200
< X-Application-Context: application:8082
< Content-Type: application/json;charset=UTF-8
< Transfer-Encoding: chunked
< Date: Sun, 15 Jul 2018 11:55:26 GMT
<
{
  "id" : 9,
  "name" : "TuwJ"
}* Connection #0 to host localhost left intact

3.2. POST

We use this method to send data to a receiving service, which means we use the data option.

The simplest way of doing this is to embed the data in the command:

curl -d 'id=9&name=baeldung' http://localhost:8082/spring-rest/foos/new

Alternatively, we can pass a file containing the request body to the data option like this:

curl -d @request.json -H "Content-Type: application/json" 
  http://localhost:8082/spring-rest/foos/new

By using the above commands as they are, we may run into error messages like the following one:

{
  "timestamp" : "15-07-2018 05:57",
  "status" : 415,
  "error" : "Unsupported Media Type",
  "exception" : "org.springframework.web.HttpMediaTypeNotSupportedException",
  "message" : "Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported",
  "path" : "/spring-rest/foos/new"
}

This is because curl adds the following default header to all POST requests:

Content-Type: application/x-www-form-urlencoded

This is also what the browsers use in a plain POST. In our usage, we’d usually want to customize the headers depending on our needs.

For instance, if our service expects JSON content-type, then we can use the -H option to modify our original POST request:

curl -d '{"id":9,"name":"baeldung"}' -H 'Content-Type: application/json' 
  http://localhost:8082/spring-rest/foos/new

Windows command prompt has no support for single quotes like the Unix-like shells.

As a result, we’d need to replace the single quotes with double quotes, though we try to escape them wherever necessary:

curl -d "{\"id\":9,\"name\":\"baeldung\"}" -H "Content-Type: application/json" 
  http://localhost:8082/spring-rest/foos/new

Besides, when we want to send a somewhat larger amount of data, it is usually a good idea to use a data file.

3.3. PUT

This method is very similar to POST, but we use it when we want to send a new version of an existing resource. In order to do this, we use the -X option.

Without any mention of a request method type, curl defaults to using GET; therefore, we explicitly mention the method type in the case of PUT:

curl -d @request.json -H 'Content-Type: application/json' 
  -X PUT http://localhost:8082/spring-rest/foos/9

3.4. DELETE

Again, we specify that we want to use DELETE by using the -X option:

curl -X DELETE http://localhost:8082/spring-rest/foos/9

4. 自定義標題

我們可以替換默認標題或添加我們自己的標題。

例如,要更改 Host 標題,我們這樣做:

curl -H "Host: com.baeldung" http://example.com/

要關閉 User-Agent 標題,我們將其設置為空值:

curl -H "User-Agent:" http://example.com/

在測試過程中最常見的場景是更改 Content-Type 和 Accept 標題。我們只需使用 -H 選項對每個標題進行前綴:

curl -d @request.json -H "Content-Type: application/json" 
  -H "Accept: application/json" http://localhost:8082/spring-rest/foos/new

5. 身份驗證

需要身份驗證的服務將會返回一個 401 – Unauthorized HTTP 響應代碼,以及相關的 WWW-Authenticate 標頭。

對於基本身份驗證,我們可以只需在請求中嵌入用户名和密碼組合,使用 user 選項即可:

curl --user baeldung:secretPassword http://example.com/

但是,如果我們想使用 OAuth2 進行身份驗證,我們首先需要從我們的授權服務獲取 access_token

服務響應將會包含 access_token:

{
  "access_token": "b1094abc0-54a4-3eab-7213-877142c33fh3",
  "token_type": "bearer",
  "refresh_token": "253begef-868c-5d48-92e8-448c2ec4bd91",
  "expires_in": 31234
}

現在我們可以使用該令牌在 Authorization 標頭中:

curl -H "Authorization: Bearer b1094abc0-54a4-3eab-7213-877142c33fh3" http://example.com/

6. 結論

在本文中,我們演示了使用curl的最低限度功能來測試我們的REST服務。雖然它可以做比這裏討論的要多得多,但對於我們的目的而言,這已經足夠了。

user avatar
0 位用戶收藏了這個故事!
收藏

發佈 評論

Some HTML is okay.