如何在Swift中打印请求NSMutableURLRequest

时间:2015-09-05 08:23:28

标签: swift alamofire swifty-json

TL;博士; 我想使用Swift

打印生成的(通过Alamofire)请求(或至少是请求正文)

我收到了NSMutableURLRequest个对象 我试过了:

Alamofire.request(.POST, URL, parameters: params)
        .responseJSON{ request, response, JSON, error in
        println(request)

但我收到(调试器输出):

(lldb) p println(request)
<NSMutableURLRequest: 0x7faac257f520> { URL: http://apphb.com/api/x }

也许description

(lldb) p println(request.description)
<NSMutableURLRequest: 0x7faac257f520> { URL: http://apphb.com/api/x}

HTTPBody? (...以下==手动缩短输出为我)

(lldb) p println(request.HTTPBody!)
<416e7377 65727325 ... 38323833>

Ecoding - 不是那么糟糕但没有格式化

(lldb) p println(NSString(data: request.HTTPBody!, encoding:NSUTF8StringEncoding)!)
Answers%5B%5D%5BAnswerId%5D=65&An...

但是我想获得完整的请求和身体作为JSON(使用SwiftyJSON?) - 如何实现它?

1 个答案:

答案 0 :(得分:12)

关于获取请求HTTPBody我在encoding: .JSON中遗漏了Alamofire.request,因此在更改为:

之后
Alamofire.request(.POST, URL, parameters: params, encoding: .JSON)
    .responseJSON{ request, response, JSON, error in

    println(NSString(data: request.HTTPBody!, encoding:NSUTF8StringEncoding)!)

我明白了:

{"Answers":[{"AnswerId" ...

或以漂亮的方式获取数据:

println(NSJSONSerialization.JSONObjectWithData(request.HTTPBody!,options:nil, error:nil)!)

提供什么

{
Answers =     (
            {
        AnswerId = 66;
        QuestionId = 22;
    },
            {
        AnswerId = ...