O-mkar
O-mkar

Reputation: 5658

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/

Upvotes: 4

Views: 1320

Answers (2)

Alex Shubin
Alex Shubin

Reputation: 3617

UnsafeMutableRawPointer will be probably killed when you go async. This will work fine:

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

        }
    }
}

Upvotes: 2

O-mkar
O-mkar

Reputation: 5658

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

Upvotes: 8

Related Questions