我正在学习swift,我需要发出GET请求,所以这是我的代码:
var j = ["user": "xxxxxx@xxxxxx.xxx"]
var e: NSError?
let jsonData = NSJSONSerialization.dataWithJSONObject(j,options: NSJSONWritingOptions(0),error: &e)
var jsonString = NSString(data: jsonData!, encoding: NSUTF8StringEncoding)
var urlPath = "http://test.example.io/materials?query=\(jsonString)";
println(urlPath)
var url: NSURL = NSURL(string: urlPath)
var request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.addValue("xxxxxxxxxxxxxxxxxxxx" , forHTTPHeaderField: "Teech-Application-Id")
request.addValue("xxxxxxxxxxxxxxxxxxxx" , forHTTPHeaderField: "Teech-REST-API-Key")
request.addValue("application/json" , forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "GET"
println(request)
这是我的输出调试
http://test.example.io/materials?query={"user":"xxxxxxxxx@xxxxxxxxx.xxxxx"}
<NSMutableURLRequest: 0x7f8ee3480320> { URL: (null), headers: {
"Content-Type" = "application/json";
"Teech-Application-Id" = xxxxxxxxxxxxxxxxxxxxxxxx;
"Teech-REST-API-Key" = xxxxxxxxxxxxxxxxxxxxxxxxx;
} }
为什么第一个打印函数返回正确的url并且在打印请求中有一个空url,哪里是我的错误?我已经尝试过没有json的url并且它运行了。
答案 0 :(得分:1)
我完成了,解决方案是逃避字符串。
var escapedSearchTerm = urlPath.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
var url: NSURL = NSURL(string: escapedSearchTerm!)