使用基本身份验证发出 http 请求 [英] Make a http request with basic authentication

查看:37
本文介绍了使用基本身份验证发出 http 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用基本身份验证发出 http 请求.我试图关注这个话题:点击这里.但是 Xcode 告诉我

I want to make an http request with basic auth. I tried to follow this topic : click here. But Xcode tell me

httpResponse 后的错误请求

Bad Request after httpResponse

我不知道为什么从今天早上开始.也许有人有比我在网上找到的更有趣的想法?:)

And I don't know why since this morning. Maybe anyone got a idea more interesting than I can find on the web ? :)

这是我的代码:

func topRefresh(sender:AnyObject){

    var list=Array<Notification>()

    //credential
    let credentialLogin = NSUserDefaults.standardUserDefaults().objectForKey("login") as! String
    let credentialPassword = NSUserDefaults.standardUserDefaults().objectForKey("password") as! String

    // set up the base64-encoded credentials
    let loginString = NSString(format: "%@:%@", credentialLogin, credentialPassword)
    let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
    let base64LoginString = loginData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)

    // create the request
    let url = NSURL(string: jsonLink)!
    let request = NSMutableURLRequest(URL: url)
    request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
    request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
    request.HTTPMethod="GET"
    let paramString="login="+credentialLogin
    request.HTTPBody = paramString.dataUsingEncoding(NSUTF8StringEncoding)

    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithRequest(request) {
        (data, response, error) -> Void in

        let httpResponse = response as! NSHTTPURLResponse

        if (httpResponse.statusCode == 200) {
            do{
                if  (data != nil){
                    self.notificationsDisplayed.removeAll()
                    let jsonDict = try NSJSONSerialization.JSONObjectWithData(data!,options: .AllowFragments)
                    list=self.parseJson(jsonDict)

                    if (self.notifications.count==0){
                        self.notifications=self.copyArray(list)
                        list.removeAll()
                    }else{
                        //compare new data with past data
                        while(list.count>0){
                            print(list.count)

                            let tmp=list.last
                            for notification in self.notifications {
                                if(tmp!.id==notification.id){
                                    list.removeLast()
                                    break
                                }else{
                                    self.notifications.insert(tmp!, atIndex: 0)
                                    list.removeLast()
                                    break
                                }
                            }
                        }
                    }
                    self.orderByDate(&self.notifications)
                    self.notificationsDisplayed=self.copyArray(self.notifications)
                    self.applyFilter()
                    print("Data parsed")
                }else{
                    print("Data is empty")
                }

            }catch {
                print("Error with Json: \(error)")
            }
        }else{
            print("HTTP Error")
        }
        self.refreshControl?.endRefreshing()
        print("Finished")
    }
    task.resume()
}

推荐答案

我在我的代码中使用以下内容来创建一个包含身份验证的默认会话:

I use the following in my code to create a default session that include the authentication:

static func defaultURLSession(username : String, password:String) -> NSURLSession {
    let config = NSURLSessionConfiguration.defaultSessionConfiguration()
    let userPasswordString = "\(username):\(password)"
    let userPasswordData = userPasswordString.dataUsingEncoding(NSUTF8StringEncoding)
    let base64EncodedCredential = userPasswordData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.EncodingEndLineWithCarriageReturn)
    let authString = "Basic \(base64EncodedCredential)"
    config.HTTPAdditionalHeaders = ["Authorization" : authString]

    return NSURLSession(configuration: config)
}

这篇关于使用基本身份验证发出 http 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆