代码之家  ›  专栏  ›  技术社区  ›  itsaboutcode

如何在NSURLConnection中设置libcurl的“CURLOPT\u USERPWD”字段

  •  1
  • itsaboutcode  · 技术社区  · 15 年前

    我试图使用NSURConnection访问一个web服务,但是我不确定如何在那里发送密码,因为php中给出的示例代码设置了libcurl的CURLOPT\u USERPWD字段,而NSURLConnection/nsurlrequest中似乎没有这样的字段。

    1 回复  |  直到 15 年前
        1
  •  2
  •   Dave DeLong    15 年前

    获取用户名和密码,并用冒号将它们连在一起。获取结果字符串并对其进行Base64编码。获取Base64编码的字符串,并在“Basic”前面加上空格。现在拿着那根绳子( Basic [Base64 encoded value] )并将其设置为请求的“授权”标头。

    或者,如果您使用 NSURLConnection 委托方法,您可以通过以下方式实现其中一种方法:

    - (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
      NSURLCredential * credential = [NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceForSession];
      [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
    }
    

    (警告:未测试,在浏览器中键入。 警告实施者