swift 如何将http请求打印到控制台

wrrgggsh  于 2022-12-26  发布在  Swift
关注(0)|答案(6)|浏览(192)

是否可以在执行实际请求之前打印整个http(s)请求?
这是我的代码:

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
})

这将首先以十六进制打印json,然后:
第一个月
这对我没有多大帮助,我只是想把我的整个请求打印出来,就像你在firebug和firefox中看到的那样。

  • --编辑--*

澄清一下,我并不想打印我的json。关于这个问题在SO上已经有足够多的问题了。我想把我的完整请求打印出来,像这样:

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

或者这个:

omhiaaxx

omhiaaxx1#

我觉得你在找这样的东西

print("\(URLRequest.httpMethod ?? "") \(URLRequest.url)")
let str = String(decoding: URLRequest.httpBody!, as: UTF8.self)
print("BODY \n \(str)")
print("HEADERS \n \(URLRequest.allHTTPHeaderFields)")
8ljdwjyq

8ljdwjyq2#

Swift 5中:

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

如果您尝试查看整个HTTP请求:

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

您可以将最后一位添加到扩展中:

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)!)
    }
}
zqdjd7g9

zqdjd7g93#

在completionHandler中打印它:

let task = session.dataTaskWithRequest(postsURLRequest) {
    data, response, error in
    //handle response
     print(NSString(data: data.HTTPBody!, encoding:NSUTF8StringEncoding)!)
}

如果它不工作,然后使用以下:

print(NSString(data: data, encoding: NSUTF8StringEncoding))
oipij1gg

oipij1gg4#

可以使用CustomStringConvertible或CustomDebugStringConvertible生成有关URLRequest扩展的说明。可以在返回字符串中包含所需的属性。

extension URLRequest /*: CustomStringConvertible*/{
    public var description: String{
        get{
            return "HEADERS \n \(String(describing: allHTTPHeaderFields))"
        }
    }
}

Use : print(<session task>.currentRequest?.description)
o3imoua4

o3imoua45#

这一个适合我:

let task = session.dataTaskWithRequest(postsURLRequest) { data, response, error in
    if let data {
        do {
            var jsonResult: NSDictionary
            try jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
            print("AsSynchronous\(jsonResult)")
        }
        catch {
            // handle error
        }
    } else {
        print("Error: no data for request \(urlPath)")
    }
}
shyt4zoc

shyt4zoc6#

let task = session.dataTaskWithRequest(postsURLRequest) {
    data, response, error in
    //handle response
     print(NSString(data: response.request, encoding:NSUTF8StringEncoding)!)
}

相关问题