swiftmacoscurlperfect

How to make post request in CURL with Perfect


I have set up a Perfect server and I have written all my API but I'm stuck at the CURL, I don't know how do I set headers I have never worked before with CURL.

I am setting up a payment gateway and I want to set authorization headers and send body data but I dont know how to.

From example 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)")
}

I referred this but got no help how to do?

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


Solution

  • After lots of searching, I found something

    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))")
    
    }
    

    For more just refer this C examples https://curl.haxx.se/libcurl/c/example.html