如何打印来自 dataTaskWithRequest 的 Web 服务请求和响应

How to print the web service request and response from dataTaskWithRequest

任何人都可以指导我如何在使用 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.

中查看它们

您可以打印 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")
    }
}

Swift 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 ""
}

已更新为 objective 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);

}
}

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

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]);

用于以 JSON 格式打印响应,以便您可以 copy/paste 将其输入 Postman 并进行检查。

在Objective C中:

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

在Swift4:

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