简体   繁体   English

Swift(或 Objective-c)相当于 curl 请求

[英]Swift(or objective-c) equivalent of curl request

I'd like to maniplate the following curl request into swift(or objective-c).我想将以下 curl 请求处理为 swift(或 Objective-c)。

curl -X POST \ -d "login_id=mylogin_id" \ 
-d "api_key=myapi_key" \ 
https://~~~~~/v2/authenticate/api

The following is what I wrote.以下是我写的。

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)
}

If the login is successful a token will be returned, however, I cannot get it.如果登录成功,将返回令牌,但是,我无法获取它。

{"auth_token": "ea6d13c7bc50feb46cf978d137bc01a2"}

I referred this link .我提到了这个链接 Thank you for your kindness.谢谢你的好意。

////// ※Update Jan4th PM2:30 ////// ※更新1月4日下午2:30

I have rewritten the code from "var request~~" as following, then get "Error", therefore it looks like this code returns urlData as nil.我已经重写了“var request~~”中的代码如下,然后得到“错误”,因此看起来这段代码将urlData返回为nil。

If you will find how to solve problem, please help me.如果您会找到解决问题的方法,请帮助我。

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");
    }

I've got the auth token by using NSURLSession on behalf of NSURLConnection, however I am still not sure why NSURLSession can be used and NSURLConnection cannot be used.我通过代表 NSURLConnection 使用 NSURLSession 获得了身份验证令牌,但是我仍然不确定为什么可以使用 NSURLSession 而不能使用 NSURLConnection。 If you have an idea, please tell me.如果你有什么想法,请告诉我。 Thank you for your kindness.谢谢你的好意。

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()
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM