如何使用完美

时间:2016-12-07 14:19:55

标签: swift macos curl perfect

我已经设置了Perfect服务器并且我已经编写了所有API,但是我仍然坚持使用CURL,我不知道如何设置我以前从未使用过的标头卷曲。

我正在设置支付网关,我想设置授权标头并发送正文数据,但我不知道如何处理。

来自示例http://perfect.org/docs/cURL.html

let curlObject = CURL(url: "http://www.perfect.org")

curlObject.perform {
    code, header, body in

    print("Request error code \(code)")
    print("Response: \(curlObject.responseCode)")
    print("Header: \(header)")
    print("Body: \(body)")
}

我提到了这个,但没有帮忙怎么办?

https://curl.haxx.se/libcurl/c/

2 个答案:

答案 0 :(得分:8)

经过大量搜索后,我发现了一些

let url = "https://httpbin.org/post"
let postParamString = "key1=value1&key2=value2"
let byteArray = [UInt8](postParamString.utf8)


let curl = CURL(url: url)

let _ = curl.setOption(CURLOPT_POST, int: 1)
let _ = curl.setOption(CURLOPT_POSTFIELDS, v: UnsafeMutableRawPointer(mutating: byteArray))
let _ = curl.setOption(CURLOPT_POSTFIELDSIZE, int: byteArray.count)

curl.perform { code, header, body in

        print("Request error code \(code) \n Response: \(curl.responseCode) \n Header: \(UTF8Encoding.encode(bytes:header)) \n Body: \(UTF8Encoding.encode(bytes: body))")

}

如需更多信息,请参阅此 C示例 https://curl.haxx.se/libcurl/c/example.html

答案 1 :(得分:2)

当您进行异步时,可能会杀死UnsafeMutableRawPointer。这样可以正常工作:

import cURL
import PerfectCURL

public class CurlHTTPRequest {

    public static func post(url: String, header: String, body: String, callback: @escaping (String)->Void) {

        let byteArray:[UInt8] = Array(body.utf8)

        let pointer = UnsafeMutablePointer<UInt8>.allocate(capacity: byteArray.count)
        pointer.initialize(from: byteArray, count: byteArray.count)

        let curlObject = CURL(url: url)
        curlObject.setOption(CURLOPT_POST, int: 1)
        curlObject.setOption(CURLOPT_HTTPHEADER, s: header)
        curlObject.setOption(CURLOPT_SSL_VERIFYPEER, int: 0)
        curlObject.setOption(CURLOPT_POSTFIELDS, v: pointer)
        curlObject.setOption(CURLOPT_POSTFIELDSIZE, int: byteArray.count)

        curlObject.perform { (code, header, body) in

            curlObject.close()

            callback("Code: \(code)\n Header: \(String(bytes: header, encoding: .utf8) ?? "")\n Body: \(String(bytes: body, encoding: .utf8) ?? "")")

        }
    }
}