Test a REST API with curl – 用curl测试一个REST API

最后修改: 2018年 7月 21日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

This tutorial gives a brief overview of testing a REST API using curl.

本教程简要介绍了使用curl.测试REST API的情况。

curl is a command-line tool for transferring data, and it supports about 22 protocols, including HTTP. This combination makes it a very good ad-hoc tool for testing our REST services.

curl是一个传输数据的命令行工具,它支持大约22种协议,包括HTTP。这种组合使它成为测试我们的REST服务的非常好的临时工具。

2. Command-line Options

2.命令行选项

curl supports over 200 command-line options. We can have zero or more of them to accompany the URL in the command.

curl支持超过200个命令行选项。我们可以有0个或更多的选项来配合命令中的URL。

Before we use it for our purposes, let’s take a look at two that would make our lives easier.

在我们将其用于我们的目的之前,让我们看一下两个会使我们的生活更容易。

2.1. Verbose

2.1.冗长

When we’re testing, it’s a good idea to set the verbose mode on:

当我们进行测试时,最好是将verbose模式设置为开启。

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

As a result, the commands provide helpful information such as the resolved IP address, the port we’re trying to connect to, and the headers.

因此,这些命令提供了有用的信息,如已解决的IP地址,我们试图连接的端口,以及头文件。

2.2. Output

2.2.输出

By default, curl outputs the response body to standard output. Additionally, we can provide the output option to save to a file:

默认情况下,curl输出响应体到标准输出。此外,我们可以提供输出选项,保存到文件中。

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

This is especially helpful when the response size is large.

这在响应规模较大时特别有帮助。

3. HTTP Methods With curl

3.使用curl的HTTP方法

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

每个HTTP请求都包含一个方法。最常用的方法是GET、POST、PUT和DELETE。

3.1. GET

3.1 GET

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

这是用 curl进行HTTP调用时的默认方法。事实上,之前展示的例子是普通的GET调用。

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

在8082端口运行一个服务的本地实例时,我们会使用类似这样的命令来进行GET调用。

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:

由于我们打开了verbose模式,我们可以得到更多的信息和响应主体。

*   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

3.2 邮政

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:

这是因为curl在所有POST请求中添加了以下默认头。

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.

这也是浏览器在普通POST中使用的内容。在我们的使用中,我们通常希望根据我们的需要来定制头信息。

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

例如,如果我们的服务希望有JSON内容类型,那么我们可以使用-H选项来修改我们的原始POST请求。

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.

Windows命令提示符不支持像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

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.

这种方法与POST非常相似,但当我们想发送一个现有资源的新版本时,我们会使用它。为了做到这一点,我们使用-X选项。

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默认使用GET;因此,我们在PUT的情况下明确提到方法类型。

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

3.4. DELETE

3.4. DELETE

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

同样,我们通过使用-X选项指定我们要使用DELETE。

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

4. Custom Headers

4.自定义页眉

We can replace the default headers or add headers of our own.

我们可以替换默认的标头或添加我们自己的标头。

For instance, to change the Host header, we do this:

例如,要改变主机头,我们这样做。

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

To switch off the User-Agent header, we put in an empty value:

为了关闭User-Agent头,我们输入了一个空值。

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

The most common scenario while testing is changing the Content-Type and Accept header. We just have to prefix each header with the -H option:

测试时最常见的情况是改变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. Authentication

5.认证

A service that requires authentication would send back a 401 – Unauthorized HTTP response code, and an associated WWW-Authenticate header.

一个需要认证的服务将发回一个401 – 未经授权的HTTP响应代码,以及一个相关的WWW-Authenticate标头。

For basic authentication, we can simply embed the username and password combination inside our request using the user option:

对于基本认证,我们可以使用用户选项将用户名和密码组合嵌入我们的请求中。

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

However, if we want to use OAuth2 for authentication, we first need to get the access_token from our authorization service.

但是,如果我们想使用OAuth2进行认证,我们首先需要从授权服务中获取access_token

The service response would contain the access_token:

服务响应将包含access_token:

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

Now we can use the token in our Authorization header:

现在我们可以在我们的授权头中使用该令牌。

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

6. Conclusion

6.结语

In this article, we demonstrated using the bare minimum functionality of curl to test our REST services. Although it can do much more than what was discussed here, for our purposes, this much should suffice.

在这篇文章中,我们演示了使用 curl的最低功能来测试我们的REST服务。虽然它能做的比这里讨论的要多得多,但对于我们的目的来说,这么多应该足够了。

Feel free to type curl -h on the command line to check out all of the available options. The REST service used for the demonstration is available here on GitHub.

请随意在命令行中输入curl -h,以查看所有的可用选项。用于演示的REST服务可在GitHub上获得这里