我想将以下卷曲请求操作为swift(或objective-c)。
curl -X POST \ -d "login_id=mylogin_id" \
-d "api_key=myapi_key" \
https://~~~~~/v2/authenticate/api
以下是我写的内容。
func authentication(){
var loginID = "mylogin_id"
var apiKey = "myapi_key"
var post:NSString = "login_id=\(loginID)&api_key=\(apiKey)"
NSLog("PostData: %@",post);
var url:NSURL = NSURL(string:"https://~~~~~/v2/authenticate/api")!
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")
var reponseError: NSError?
var response: NSURLResponse?
var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)
}
如果登录成功,将返回一个令牌,但是,我无法得到它。
{"auth_token": "ea6d13c7bc50feb46cf978d137bc01a2"}
我提到this link。 谢谢你的好意。
////// ※1月4日PM2:30更新
我已经重写了#34; var request ~~"如下所示,然后得到"错误",因此看起来这段代码将urlData返回为nil。
如果您将找到解决问题的方法,请帮助我。
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")
var reponseError: NSError?
var response: NSURLResponse?
var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)
if (urlData != nil){
var responseData:NSString = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!
let res = response as NSHTTPURLResponse!;
NSLog("Response code: %ld", res.statusCode);
if (res.statusCode >= 200 && res.statusCode < 300){
var responseData:NSString = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!
NSLog("Response ==> %@", responseData);
}
}else{
NSLog("Error");
}
答案 0 :(得分:1)
我代表NSURLConnection使用NSURLSession获得了身份验证令牌,但我仍然不确定为什么可以使用NSURLSession并且无法使用NSURLConnection。 如果您有任何想法,请告诉我。谢谢你的好意。
func authentication2(){
let request = NSMutableURLRequest(URL: NSURL(string: "https://~~~/v2/authenticate/api")!)
request.HTTPMethod = "POST"
var loginID = "mylogin_id"
var apiKey = "myapi_key"
var postString:NSString = "login_id=\(loginID)&api_key=\(apiKey)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
println("error=\(error)")
return
}
println("response = \(response)")
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("responseString = \(responseString)")
}
task.resume()
}