我从 HTTP 代理客户端发送相同的 HTTP 消息并使用 NSURLRequest
+ NSURLConnection
,并返回不同的结果。这是一个身份验证请求。从 HTTP 代理身份验证请求被接受,而不是从应用程序发送。为什么?接受意味着重定向后 HTML 将不包含 Oops
子字符串。
let url = NSURL(string: "http://www.swisshttp.weact.ch/en/user/login")
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let email2 = (viewController!.email.text as NSString).stringByReplacingOccurrencesOfString("@", withString: "%40")
let str = "name=\(email2)&pass=\(viewController!.password.text)&form_id=user_login" as NSString
let d = str.dataUsingEncoding(NSUTF8StringEncoding)
if let d2 = d {
request.HTTPBody = d2
let urlConnection = NSURLConnection(request: request, delegate: self)
}
更新
我已将下面@teamnorge 的代码放入 playground 和一个空的单 View 应用程序项目中。项目中返回的 HTML 包含 Oops
子字符串,playground 中使用的代码不包含它,知道发生了什么,为什么相同的请求产生不同的 HTML 结果?我也从 iOS 设备和模拟器收到 failed
消息。
更新
删除了 NSURLRequest
缓存,如 here推荐,但仍未按预期工作。和 here .
更新
试图删除所有凭证,如 here ,但没有帮助,找不到凭据。
最佳答案
看起来当您收到 HTTP 302 和新的 Location URL 时,iOS 会自动通过该 URL 获取页面,所以我猜您的响应实际上是重定向页面的 HTML 内容。请验证。
更新:
import UIKit
import XCPlayground
let url = NSURL(string: "http://www.swisshttp.weact.ch/en/user/login")
let request = NSMutableURLRequest(URL: url!)
let str = "name=kukodajanos%40icloud.com&pass=jelszo&form_id=user_login" as NSString
let d = str.dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPBody = d
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.currentQueue()) { response, maybeData, error in
if let data = maybeData {
let contents = NSString(data:data, encoding:NSUTF8StringEncoding)
println(contents)
if contents!.rangeOfString("Oops").length == 0 {
println("success")
} else {
println("failed")
}
} else {
println(error.localizedDescription)
}
}
XCPSetExecutionShouldContinueIndefinitely()
关于ios - NSURLRequest 产生与 HTTP 代理客户端不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31587315/