Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 887
O-mkar Avatar asked Dec 23 '22 22:12

O-mkar


2 Answers

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

like image 94
O-mkar Avatar answered Dec 28 '22 06:12

O-mkar


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

        }
    }
}
like image 35
Alex Shubin Avatar answered Dec 28 '22 06:12

Alex Shubin