我从HTTP代理客户端和NSURLRequest NSURLConnection发送相同的HTTP消息,并获得不同的结果.它是一个认证请求.从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) }
UPDATE
我把@ teamnorge的代码放在操场上,进入一个空的Single View Application项目.项目中返回的HTML包含Oops子字符串,在操场中使用的代码不包含它,任何想法发生了什么,为什么同样的请求会产生不同的HTML结果?我也从iOS设备和模拟器也收到失败的消息.
UPDATE
删除NSURLRequest缓存,如here推荐,但仍然无法正常工作.和here.
UPDATE
解决方法
看起来当您收到HTTP 302和新的位置网址时,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()