如何在 Vapor 3 中进行第三方 api 调用?

How to make a third party api call in Vapor 3?

我想用 Vapor 3 中的一些参数进行 post 调用。

POST: http://www.example.com/example/post/request

title: How to make api call
year: 2019

哪个package/function可以用?

这很简单,您可以像这样使用 Client 来做到这一点

func thirdPartyApiCall(on req: Request) throws -> Future<Response> {
    let client = try req.client()
    struct SomePayload: Content {
        let title: String
        let year: Int
    }
    return client.post("http://www.example.com/example/post/request", beforeSend: { req in
        let payload = SomePayload(title: "How to make api call", year: 2019)
        try req.content.encode(payload, as: .json)
    })
}

或例如像这样 boot.swift

/// Called after your application has initialized.
public func boot(_ app: Application) throws {    
    let client = try app.client()
    struct SomePayload: Content {
        let title: String
        let year: Int
    }
    let _: Future<Void> = client.post("http://www.example.com/example/post/request", beforeSend: { req in
        let payload = SomePayload(title: "How to make api call", year: 2019)
        try req.content.encode(payload, as: .json)
    }).map { response in
        print(response.http.status)
    }
}