无法将Authorization标头作为服务器响应401发送

时间:2017-11-27 06:37:13

标签: swift3

以下代码中没有编译错误。

但是,我从服务器收到了消息:401

这意味着服务器无法接收我发送的标题。

但是我的Auhtorization标头包含此值:      var strToken = strToken1 +“,”+ strToken2 +“,Basic”+ strBase64Credential

更新

strBase64Credential是:用户名和密码

strToken1和strToken2不是用户名和密码

What I did wrong and Why server did not receive the header values?


in plist : I added this :

<key>NSAppTransportSecurity</key>
 <dict>
   <key>NSAllowsArbitraryLoads</key>
   <true/>
 </dict>




 var request = URLRequest(url: StrURL)

 var strToken = strToken1 + ", " + strToken2 + ", Basic " + strBase64Credential 

 request.httpMethod = "GET"
 request.setValue("application/json", forHttpHeaderField:"Content-type")

 request.setValue(strToken, forHTTPHeaderField: "Authorization")

 let session = URLSession.shared

 session.addTask(with: request) { (data,response,error) in 

    if let response = response {

     print(response)
    } else {

      return 

    }

   if let data = data{

     //-- handle data here

   }

}.resume()

请帮忙。

1 个答案:

答案 0 :(得分:0)

请尝试此代码。 strToken1与userName和strToken2一样作为密码。此格式用于基本身份验证过程。

  let basicAuthString = "\(userName):\(password)"
  let utf8str = basicAuthString.dataUsingEncoding(NSUTF8StringEncoding)
  let base64EncodedString = utf8str?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(0))

  request.addValue("Basic \(base64EncodedString!)", forHTTPHeaderField: "Authorization")