是否可以将NSURLSession发送的请求记录到控制台?我遇到了身份验证问题,如果我无法查看请求,则无法调试
答案 0 :(得分:9)
这些方法将以干净的方式打印HTTP请求和响应:
class func log(request: URLRequest){
let urlString = request.url?.absoluteString ?? ""
let components = NSURLComponents(string: urlString)
let method = request.httpMethod != nil ? "\(request.httpMethod!)": ""
let path = "\(components?.path ?? "")"
let query = "\(components?.query ?? "")"
let host = "\(components?.host ?? "")"
var requestLog = "\n---------- OUT ---------->\n"
requestLog += "\(urlString)"
requestLog += "\n\n"
requestLog += "\(method) \(path)?\(query) HTTP/1.1\n"
requestLog += "Host: \(host)\n"
for (key,value) in request.allHTTPHeaderFields ?? [:] {
requestLog += "\(key): \(value)\n"
}
if let body = request.httpBody{
requestLog += "\n\(NSString(data: body, encoding: String.Encoding.utf8.rawValue)!)\n"
}
requestLog += "\n------------------------->\n";
print(requestLog)
}
class func log(data: Data?, response: HTTPURLResponse?, error: Error?){
let urlString = response?.url?.absoluteString
let components = NSURLComponents(string: urlString ?? "")
let path = "\(components?.path ?? "")"
let query = "\(components?.query ?? "")"
var responseLog = "\n<---------- IN ----------\n"
if let urlString = urlString {
responseLog += "\(urlString)"
responseLog += "\n\n"
}
if let statusCode = response?.statusCode{
responseLog += "HTTP \(statusCode) \(path)?\(query)\n"
}
if let host = components?.host{
responseLog += "Host: \(host)\n"
}
for (key,value) in response?.allHeaderFields ?? [:] {
responseLog += "\(key): \(value)\n"
}
if let body = data{
responseLog += "\n\(NSString(data: body, encoding: String.Encoding.utf8.rawValue)!)\n"
}
if error != nil{
responseLog += "\nError: \(error!.localizedDescription)\n"
}
responseLog += "<------------------------\n";
print(responseLog)
}
示例:强>
---------- OUT ---------->
https://api.example.com/api/auth
POST /api/auth HTTP/1.1
Host: api.example.com
------------------------->
<---------- IN ----------
https://api.example.com/api/auth
HTTP/1.1 200 /api/auth
Host: api.example.com
Content-Type: application/json; charset=UTF-8
Content-Length: 331
Date: Mon, 21 Aug 2017 18:55:46 GMT
Server: Google Frontend
{
"Data": {
"Token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MDMzNDUzNDYsImlhdCI6MTUwMzM0MTc0NiwianRpIjoiNTcwNmMyN2UtODZhMi0xMWU3LThkN2ItNjJjYmY2YzkxYzdhIiwibmJmIjoxNTAzMzQxNzQ2fQ.0p09QG9ImjemQxlDIxZb9SL6j3Fy4VAAzsA-JZp27q0",
"ExpiryUnix": 1503345346,
"ExpiryTimestamp": "Mon Aug 21 19:55:46 UTC 2017"
}
}
<------------------------
答案 1 :(得分:2)
打印请求正文的一种可能方法是:
let sBody = NSString(data: request.HTTPBody!, encoding: NSASCIIStringEncoding)
print(sBody)
打印所有标题:
let sHeaderFields = request.allHTTPHeaderFields
print(sHeaderFields)
答案 2 :(得分:2)
值得尝试将CFNETWORK_DIAGNOSTICS = 3添加到Xcode方案中用于运行的环境变量。此处更多信息:https://developer.apple.com/library/archive/qa/qa1887/_index.html
答案 3 :(得分:0)
以下方法对我有用。对于请求体,我得到原始的ascii值,对于头字段,我使用String(描述:)函数将头值作为字符串。
斯威夫特3:
print("REQUEST BODY: \(NSString(data: request.httpBody!, encoding: String.Encoding.ascii.rawValue)!)")
print("REQUEST HEADER: \(String(describing: request.allHTTPHeaderFields!))")
控制台输出:
请求身体:{“饲料”:[“xxxx”]} REQUEST HEADER:[“Content-Type”:“application / json”,“Authorization”:“Token token = xxxxxxxxxxxxxxxxxxxxxxxxx”]
另一种方法可能是use a tool like Postman来构建您的请求并查看API响应。有一个免费版本,一旦你超越学习曲线,它在使用API时是必不可少的。
h / t @William Kinaan。他让我朝着正确的方向前进。