如何解决如何从“ http://www.google.com”打印html响应
我有一个小操场,如果我尝试请求http://www.bbc.com页面,我将获得一个有效的数据对象,并且可以看到响应数据的文本字符串表示形式。
但是,如果我请求http://www.google.com页面,则会得到一个有效的响应数据对象,但它在utf8中的字符串表示形式(使用String(data: responseData,encoding: .utf8)
为nil。
为什么呢?
import Foundation
import PlaygroundSupport
URLCache.shared = URLCache(memoryCapacity: 0,diskCapacity: 0,diskPath: nil)
PlaygroundPage.current.needsIndefiniteExecution = true
let testUrl = "http://www.google.com"
guard let url = URL(string: testUrl) else {
print("Error: cannot create URL")
exit(1)
}
let session = URLSession.shared
let urlRequest = URLRequest(url: url)
let task = session.dataTask(with: urlRequest) { (data,response,error) in
// check for any errors
guard error == nil else {
print("error calling GET ")
print(error!)
return
}
// make sure we got data
guard let responseData = data else {
print("Error: did not receive data")
return
}
// check the status code
guard let httpResponse = response as? HTTPURLResponse else {
print("Error: It's not a HTTP URL response")
return
}
// Reponse status
print("Response status code: \(httpResponse.statusCode)")
print("Response status debugDescription: \(httpResponse.debugDescription)")
print("Response status localizedString: \(HTTPURLResponse.localizedString(forStatusCode: httpResponse.statusCode))")
let responseDataStr = String(data: responseData,encoding: .utf8)
print (" responseData: \(String(describing: responseDataStr)) ")
PlaygroundPage.current.finishExecution()
}
task.resume()
````
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。