我的应用页面有一个表单,我希望用户输入他的姓名和电话号码。
我希望将此数据提取到以下网址中。
变量是用户名,phoneno。
var url:NSURL = NSURL(string: "https:xyz.com/newRequest?fullname=\(username)&phone=\(phoneno)")!
这是使用用户名和phonenumber参数作为变量编写URL的正确语法。
这是我想要实现的,但我在模拟过程中不断收到错误405 -
var post:NSString = "username=\(username)&phoneno=\(phoneno)"
NSLog("PostData: %@",post);
var url:NSURL = NSURL(string: "https://example.com/newRequest?fullname=(username)&phone=(phoneno)")!
var postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!
var postLength:NSString = String( postData.length )
var request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.HTTPBody = postData
request.setValue(postLength, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
答案 0 :(得分:2)
您应该使用NSURLComponents代替NSURLQueryItem。然后系统可以为您正确地转义值。像这样:
let username = "foo"
let phoneno = "bar"
let comps = NSURLComponents(string: "https://example.com/newRequest")
comps?.queryItems = [
NSURLQueryItem(name: "fullname", value: username),
NSURLQueryItem(name: "phone", value: phoneno)
]
comps?.URL // returns https://example.com/newRequest?fullname=foo&phone=bar