2016-05-20 8 views
0

Ich möchte eine HTTP-Anfrage mit Basic Auth. Ich habe versucht, diesem Thema zu folgen: click here. Aber sagen Sie mir XcodeMachen Sie eine HTTP-Anfrage mit Standardauthentifizierung

Bad Request nach httpresponse

Und ich weiß nicht, warum seit heute Morgen. Vielleicht hat jemand eine Idee interessanter als ich im Internet finden kann? :)

Hier ist mein Code:

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

Antwort

0

ich folgende in meinem Code verwenden, um eine Standardsitzung zu erstellen, die die Authentifizierung umfassen:

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

Wie kann ich diese Funktion in meinem eigentlichen verwenden Code? –

+0

Ich muss eine Sitzung anstelle der Anfrage verwenden, um den Benutzer zu authentifizieren? –

Verwandte Themen