Skip to content

Instantly share code, notes, and snippets.

@novinfard
Forked from dedeexe/URLRequest+curlCommand.swift
Last active April 22, 2020 15:28
Show Gist options
  • Save novinfard/15035d8ad09badbf96d6a73a11ed66f6 to your computer and use it in GitHub Desktop.
Save novinfard/15035d8ad09badbf96d6a73a11ed66f6 to your computer and use it in GitHub Desktop.
Convert URL Request to curl command
extension URLRequest {
public func curl(pretty:Bool = false) -> String {
var data : String = ""
let complement = pretty ? "\\\n" : ""
let method = "-X \(self.httpMethod ?? "GET") \(complement)"
let url = "\"" + (self.url?.absoluteString ?? "") + "\""
var header = ""
if let httpHeaders = self.allHTTPHeaderFields, httpHeaders.keys.count > 0 {
for (key,value) in httpHeaders {
header += "-H \"\(key): \(value)\" \(complement)"
}
}
if let bodyData = self.httpBody, let bodyString = String(data:bodyData, encoding:.utf8) {
data = "-d \"\(bodyString)\" \(complement)"
}
let command = "curl -i " + complement + method + header + data + url
return command
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment