swift

how to print http request to console


Is it possible to print the whole http(s) request just before doing the actual request?

This is my code:

let postsEndpoint: String = "https://www.example.com/api/"
guard let postsURL = NSURL(string: postsEndpoint) else {
    throw APICallError.other("cannot create URL")
}
let postsURLRequest = NSMutableURLRequest(URL: postsURL)
postsURLRequest.HTTPMethod = "POST"
print(UTF8EncodedJSON)
postsURLRequest.HTTPBody = UTF8EncodedJSON
print(postsURLRequest) 

let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)

let task = session.dataTaskWithRequest(postsURLRequest, completionHandler: {
    (data, response, error) in
    //handle response
})

this prints the json in hex first and then:

<NSMutableURLRequest: 0x7fdae8d1dd30> { URL: https://www.ritzie.nl/api/v2 }

which doesn't help me much. I just want to have my whole request printed like you would see it in firebug on firefox for example.

--edit--

To clarify, I'm not trying to print my json. There's enough questions about that on SO already. I want my full request printed out something like this:

POST /api/v2/ HTTP/1.1

HTTP headers:
Host: www.example.ocm
Origin: http://www.example.com
Connection: keep-alive
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/\*;q=0.8
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9
Referer: http://www.ritzie.nl/api/test.php
Accept-Language: en-us
Accept-Encoding: gzip, deflate

request body:
data=%7B%22action%22%3A+%22vehicleRecords%22%2C%0D%0A%22token%22%3A+%22token_04e01fdc78205f0f6542bd523519e12fd3329ba9%22%2C%0D%0A%22vehicle%22%3A+%22vehicle_e5b79b2e%22%7D

or this:

Firebug request screenshot


Solution

  • In Swift 5:

    URLSession.shared.dataTask(with: request) { data, response, error in
      print(String(data: data, encoding: .utf8)!)
    }
    

    If you are trying to see the whole HTTP request:

    print("\(request.httpMethod!) \(request.url!)")
    print(request.allHTTPHeaderFields!)
    print(String(data: request.httpBody ?? Data(), encoding: .utf8)!)
    

    You can add this last bit into an extension:

    fileprivate extension URLRequest {
        func debug() {
            print("\(self.httpMethod!) \(self.url!)")
            print("Headers:")
            print(self.allHTTPHeaderFields!)
            print("Body:")
            print(String(data: self.httpBody ?? Data(), encoding: .utf8)!)
        }
    }