【问题标题】:How to print the web service request and response from dataTaskWithRequest如何打印来自 dataTaskWithRequest 的 Web 服务请求和响应
【发布时间】:2018-02-26 05:27:16
【问题描述】:

谁能指导我如何在使用 swift 4.0 和 Objective C 时以 json 格式打印来自 dataTaskWithRequest 的 Web 服务请求和响应。

链接尝试:

How to print NSMutableURLRequest?

我可以打印它们,但它不能以正确的格式打印。我需要一种格式,以便我可以将其粘贴到邮递员或网络浏览器中并进行测试。

我需要的请求格式:

例如:https://restcountries.eu/rest/v2/name/aruba?fullText=true

回复:

需要类似上述url的响应格式,我可以在http://jsonviewer.stack.hu查看。

【问题讨论】:

  • 使用邮递员。你可以变得更容易
  • 谢谢@McDonal_11...使用邮递员很容易,但我需要在控制台中打印它们。有可能吗?
  • 谢谢 Vikky,让我试试……我会告诉你的……但是你能不能把目标 C 发给我
  • @PrajnaranjanDas 检查我的答案我已经编辑了它

标签: ios json swift nsurlsessiondatatask


【解决方案1】:

获取字符串和字典对象中的响应对象:

NSURLSessionDataTask *task = [session dataTaskWithRequest:URLRequest
                                                completionHandler:
                                      ^(NSData *data, NSURLResponse *response, NSError *error) 
{ 
    // your code 

    NSString *responseString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];

    id responseObjects = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
}

从 NSData 对象或字典中获取漂亮的打印 json 格式:

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:yourDictionary
                                                   options:NSJSONWritingPrettyPrinted
                                                     error:&error];

NSString *strData = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"Params : %@", strData);

编辑

要打印 json 请求,请尝试使用:

// for POST/JSON type

NSLog(@"Request body %@", [[NSString alloc] initWithData:[request HTTPBody] encoding:NSUTF8StringEncoding]);

// for GET type

NSLog(@"Request url : %@", [[request.URL absoluteString] stringByRemovingPercentEncoding]);

【讨论】:

  • @Prajnaranjan Das,请在此处查看我的编辑以获取打印请求。
  • 谢谢@Ami Patel ...但是上面的行只打印参数...我已经编辑了我的问题...我需要这种方式的请求格式,以便我可以粘贴到邮递员或网络浏览器并测试...
  • @PrajnaranjanDas ok 所以你需要打印一个 GET 请求。一旦我找到方法,将更新相同。但至少您可以提及您需要的响应格式,如果它对您有帮助的话。 :)
  • 谢谢@Ami...您的函数给出这样的响应,例如::::::Response: "First_Approver_Code" = CP0001; "First_Name" = PDAs; FlightDurationWindows = { 持续时间 = 8; };它应该打印 json 文件,我可以将其复制并粘贴到 jsonviewer 中并检查...
  • @PrajnaranjanDas 好的,我找到了一些打印请求。我正在更新答案,将其与您生成的请求 url 一起使用。
【解决方案2】:

斯威夫特 4

使用此功能打印您的请求。 只需将您的请求传递给此函数并记住您的请求应该是字典。

   func prettyPrintRequest(with json: [String : Any]) -> String{
    let data = try! JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
    let string = String(data: data, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
    if let string  = string{

        return string
    }
    print("something went wrong")
    return ""
}

更新到目标 c 代码

-(void)prettyPrintRequest:(NSDictionary*)request{
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:request
                                                   options:NSJSONWritingPrettyPrinted
                                                     error:&error];

if (jsonData) {
     NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSLog(@"Valid Json String is %@", jsonString);

} else {
    NSLog(@"Error is : %@", error);

}
}

【讨论】:

    【解决方案3】:

    您可以打印 JSON 数据,例如,

    if error == nil {
        do {
            let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments)
            print(json)
            let dic = json as! NSDictionary
            print(dic)
        }
        catch {
            print("Throw error when convert to json")
        }
    }
    

    【讨论】:

    • 谢谢@Kamani Jasmin...但它没有以正确的 json 格式打印...它打印如下: Agent = { "Curr_Code" = INR; “OF_ID” = 141; “TA_Account_Freezed” = 0; "TA_CL_Amount" = "110010990464157.00"; “TA_ID” = 3373; “用户 ID” = 123555; };
    • @PrajnaranjanDas 是的,因为它是一本字典。但是为什么在字典中的键值对也相同的情况下需要打印 json 呢?
    • @TheTiger...我想在 json 查看器中检查它们...这更容易阅读...在其中我可以使用大 json 展开和折叠任何数组和字典..
    • @PrajnaranjanDas Json 查看器还提供来自 URL 的 JSON 为什么您需要以编程方式执行它?您可以使用 chrome 的 Postman 扩展名或 http://hurl.it/ 来查看响应。
    • @TheTiger...是的,我知道...但是我在这里问了同样的问题...如何打印完整的请求 URL ???...
    【解决方案4】:

    用于以 JSON 格式打印响应,以便您可以将其复制/粘贴到 Postman 并检查。

    在目标 C 中

    NSString* jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSLog(@"jsonString: %@", jsonString);
    

    在 Swift 4 中

    let dataString = String(data: data, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))!
    print(dataString)
    

    【讨论】:

      猜你喜欢
      • 2012-05-07
      • 2020-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 2014-09-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多