杨锴
2025-03-11 90dc3329d1973fda691e357cf4523d5c7c67fa1d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// URLRequestExtensions.swift - Copyright 2024 SwifterSwift
 
#if canImport(Foundation)
import Foundation
 
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
 
// MARK: - Initializers
 
public extension URLRequest {
    /// SwifterSwift: Create URLRequest from URL string.
    ///
    /// - Parameter urlString: URL string to initialize URL request from
    init?(urlString: String) {
        guard let url = URL(string: urlString) else { return nil }
        self.init(url: url)
    }
 
    /// SwifterSwift: cURL command representation of this URL request.
    var curlString: String {
        guard let url else { return "" }
 
        var baseCommand = "curl \(url.absoluteString)"
        if httpMethod == "HEAD" {
            baseCommand += " --head"
        }
 
        var command = [baseCommand]
        if let method = httpMethod, method != "GET", method != "HEAD" {
            command.append("-X \(method)")
        }
 
        if let headers = allHTTPHeaderFields {
            for (key, value) in headers where key != "Cookie" {
                command.append("-H '\(key): \(value)'")
            }
        }
 
        if let data = httpBody,
           let body = String(data: data, encoding: .utf8) {
            command.append("-d '\(body)'")
        }
 
        return command.joined(separator: " \\\n\t")
    }
}
 
// MARK: - Methods
 
public extension URLRequest {
    /// SwifterSwift: Duplicates the request and modifies the HTTP method (verb) for the request (i.e.: GET, POST, PUT)
    ///
    ///     let request = URLRequest(url: url)
    ///         .method("post")
    ///
    /// - Parameter methodString: The method as a String value
    /// - Returns: The modified request
    func method(_ methodString: String) -> Self {
        var request = self
        request.httpMethod = methodString.uppercased()
        return request
    }
 
    /// SwifterSwift: Duplicates the request and set a header with key and value
    ///
    ///     let request = URLRequest(url: url)
    ///         .header(name: "Content-Type", value: "application/json")
    ///
    /// - Parameters:
    ///   - name: The name of the header
    ///   - value: The value of the header
    /// - Returns: The modified request
    func header(name: String, value: String) -> Self {
        var request = self
        request.setValue(value, forHTTPHeaderField: name)
        return request
    }
}
 
#endif