Skip to content

Instantly share code, notes, and snippets.

@peterprokop
Last active August 29, 2022 15:40
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save peterprokop/16790dfa1320211b20c94a3f4dd95464 to your computer and use it in GitHub Desktop.
Save peterprokop/16790dfa1320211b20c94a3f4dd95464 to your computer and use it in GitHub Desktop.
Print NSURLRequest in cURL format (Swift 3)
//
// URLRequest.swift
//
// Created by Peter Prokop on 17/08/2017.
import Foundation
public extension URLRequest {
/// Returns a cURL command for a request
/// - return A String object that contains cURL command or "" if an URL is not properly initalized.
public var cURL: String {
guard
let url = url,
let httpMethod = httpMethod,
url.absoluteString.utf8.count > 0
else {
return ""
}
var curlCommand = "curl --verbose \\\n"
// URL
curlCommand = curlCommand.appendingFormat(" '%@' \\\n", url.absoluteString)
// Method if different from GET
if "GET" != httpMethod {
curlCommand = curlCommand.appendingFormat(" -X %@ \\\n", httpMethod)
}
// Headers
let allHeadersFields = allHTTPHeaderFields!
let allHeadersKeys = Array(allHeadersFields.keys)
let sortedHeadersKeys = allHeadersKeys.sorted(by: <)
for key in sortedHeadersKeys {
curlCommand = curlCommand.appendingFormat(" -H '%@: %@' \\\n", key, self.value(forHTTPHeaderField: key)!)
}
// HTTP body
if let httpBody = httpBody, httpBody.count > 0 {
let httpBodyString = String(data: httpBody, encoding: String.Encoding.utf8)!
let escapedHttpBody = URLRequest.escapeAllSingleQuotes(httpBodyString)
curlCommand = curlCommand.appendingFormat(" --data '%@' \\\n", escapedHttpBody)
}
return curlCommand
}
/// Escapes all single quotes for shell from a given string.
static func escapeAllSingleQuotes(_ value: String) -> String {
return value.replacingOccurrences(of: "'", with: "'\\''")
}
}
@yashbedi
Copy link

yashbedi commented Apr 28, 2020

Awesome effort Peter really appreciate man.!!

Though a quick Suggestion :

.....
let allHeadersFields = allHTTPHeaderFields ?? ["":""] -- Line 33
.....
curlCommand = curlCommand.appendingFormat(" -H '%@: %@' \\\n", key, self.value(forHTTPHeaderField: key) ?? "") -- Line 37
.....

Using Null Coalescing Operator, coz force unwrap crashes sometimes. =)

@abhi21git
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment