HTTP clients send requests to remote HTTP servers which then generate and return responses. HTTP clients are usually only active for a matter of seconds to minutes and may send one or more requests. The
HTTPClient type is what powers Vapor's higher-level client. This short guide will show you how to send HTTP requests to servers manually.
If you are using Vapor, you probably don't need to use HTTP's APIs directly. Refer to Vapor → Client for the more convenient APIs.
For this example, we will fetch Vapor's homepage. The first step is to create a connected HTTP client. Use the static
connect(...) method to do this.
// Connect a new client to the supplied hostname. let client = try HTTPClient.connect(hostname: "vapor.codes", on: ...).wait() print(client) // HTTPClient // Create an HTTP request: GET / let httpReq = HTTPRequest(method: .GET, url: "/") // Send the HTTP request, fetching a response let httpRes = try client.send(httpReq).wait() print(httpRes) // HTTPResponse
Take note that we are passing the hostname. This is different from a full URL. You can use
URLComponents from Foundation to parse out a hostname. Vapor's convenience APIs do this automatically.
If you are creating a totally standalone client (not tying into the rest of Vapor) then you can create one of
MultiThreadedEventLoopGroup and pass it in to the
This guide assumes you are on the main thread. Don't use
wait() if you are inside of a route closure. See Async → Overview for more information.
After we have a connected HTTP client, we can send an
send(...). This will return an
HTTPResponse containing the headers and body sent back from the server. See HTTP → Message for more information on HTTP messages.
That's it! Congratulations on making your first HTTP request. Check out the API docs for more in-depth information about all of the available parameters and methods.