mirror of https://github.com/vapor/docs.git
Translated client.md into Japanese
This commit is contained in:
parent
95aa212df1
commit
df5c02a82f
|
|
@ -0,0 +1,74 @@
|
|||
# クライアント
|
||||
|
||||
Vapor のクライアント API では、外部のリソースに対して HTTP 通信を行うことができます。これは [async-http-client](https://github.com/swift-server/async-http-client) に基づいており、[コンテンツ](content.ja.md) API と統合されています。
|
||||
|
||||
## 概要
|
||||
|
||||
`Application` やルートハンドラー内の `Request` から、デフォルトクライアントにアクセスできます。
|
||||
|
||||
```swift
|
||||
app.client // Client
|
||||
|
||||
app.get("test") { req in
|
||||
req.client // Client
|
||||
}
|
||||
```
|
||||
|
||||
アプリケーションのクライアントは、設定時に HTTP リクエストを送る際に便利です。ルートハンドラー内で HTTP リクエストを行う場合は、リクエストに紐づくクライアントを使うべきです。
|
||||
|
||||
### メソッド
|
||||
|
||||
`GET` リクエストを行う際には、目的の URL を `get` メソッドに渡します。
|
||||
|
||||
```swift
|
||||
let response = try await req.client.get("https://httpbin.org/status/200")
|
||||
```
|
||||
|
||||
`get`、`post`、`delete` など、各種 HTTP メソッドに対応したメソッドがあります。クライアントからのレスポンスは将来的に返され、HTTPステータス、ヘッダー、ボディが含まれます。
|
||||
|
||||
### コンテンツ
|
||||
|
||||
Vapor の [コンテンツ](content.ja.md) を使うと、クライアントリクエストやレスポンスのデータを扱うことができます。コンテンツやクエリパラメータをエンコードしたり、ヘッダーを追加するには、`beforeSend` クロージャを使います。
|
||||
|
||||
```swift
|
||||
let response = try await req.client.post("https://httpbin.org/status/200") { req in
|
||||
// リクエストURLにクエリ文字列をエンコードします。
|
||||
try req.query.encode(["q": "test"])
|
||||
|
||||
// JSONをリクエストボディにエンコードします。
|
||||
try req.content.encode(["hello": "world"])
|
||||
|
||||
// リクエストに認証ヘッダーを追加します。
|
||||
let auth = BasicAuthorization(username: "something", password: "somethingelse")
|
||||
req.headers.basicAuthorization = auth
|
||||
}
|
||||
//レスポンスを扱う
|
||||
```
|
||||
|
||||
レスポンスボディを `Content` を使ってデコードすることもできます。:
|
||||
|
||||
```swift
|
||||
let response = try await req.client.get("https://httpbin.org/json")
|
||||
let json = try response.content.decode(MyJSONResponse.self)
|
||||
```
|
||||
|
||||
もし、futures を使っている場合は、`flatMapThrowing` を使うことができます。:
|
||||
|
||||
```swift
|
||||
return req.client.get("https://httpbin.org/json").flatMapThrowing { res in
|
||||
try res.content.decode(MyJSONResponse.self)
|
||||
}.flatMap { json in
|
||||
// Use JSON here
|
||||
}
|
||||
```
|
||||
|
||||
## 設定
|
||||
|
||||
アプリケーションを通じて、基本となる HTTP クライアントを設定することができます。
|
||||
|
||||
```swift
|
||||
// Disable automatic redirect following.
|
||||
app.http.client.configuration.redirectConfiguration = .disallow
|
||||
```
|
||||
|
||||
初めてデフォルトクライアントを使用する前に、必ず設定を完了させておく必要があります。
|
||||
Loading…
Reference in New Issue