【问题标题】:NSURLSession Authorization with post requestNSURLSession 授权与发布请求
【发布时间】:2014-08-14 11:39:43
【问题描述】:

当我尝试使用 NSURLSession 和 dataTaskWithRequest(我正在使用自定义委托)在没有(www-authorization)的情况下发出发布请求时。

效果很好。 (我发送请求,在服务器上我只打印 echo $_POST['name'] 并得到“名称”作为响应。)

当我尝试使用 (www-authorization) 发出帖子请求时,它看起来工作正常

如果我输入正确的用户名和密码,我会得到带有状态码 200 和 json 数据的标题,如果我输入错误,我会得到带有状态码 401 的标题。 在服务器端我做了

if (!isset($_SERVER['PHP_AUTH_USER'])) {
header('WWW-Authenticate: Basic realm="Realm"');
header('HTTP/1.0 401 Unauthorized');        
exit;
}
else
{
    $user = new btuser($_SERVER["PHP_AUTH_USER"],$_SERVER['PHP_AUTH_PW']);
    if ($user->logToDB())
    {
       header('content-type:application/json');
       header('test-login: '.$user->getname());         
       $array = array("fff"=>"tttt",
      "ddd"=>"qqqq",
      "uuuu"=>$_post['name']        
      );
      echo json_encode($array);    
    }
    else
    {
    header('HTTP/1.0 401 Unauthorized');
    unset($_SERVER['PHP_AUTH_USER']);        
    }                   
}

,但是“发布”请求在某处丢失了)))......我得到了这样的东西 - {“fff”:“tttt”,“ddd”:“qqqq”,“uuuu”:null}。

所有受委托人的方法看起来都很好...... 第一种方法是

1.

-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:        (int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:        (int64_t)totalBytesExpectedToSend{  
 NSLog(@"did send body data");
}

2.

 -(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task      didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler{
NSLog(@"challenge");
    NSURLCredential* newCredintioal;
    newCredintioal = [NSURLCredential credentialWithUser:@"testuser" password:@"testpassword" persistence:NSURLCredentialPersistenceForSession];
      [[challenge sender] useCredential:newCredintioal forAuthenticationChallenge:challenge];
    completionHandler(NSURLSessionAuthChallengeUseCredential,newCredintioal);
}

3 然后又是 didSendBodyData。

4

 -(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask      didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
 {
 NSLog(@"did receive response %@", response);
 completionHandler(NSURLSessionResponseAllow);

 NSURLRequest* req = dataTask.currentRequest;
 NSData* dt = [req HTTPBody];
 NSString* body = [[NSString alloc] initWithData:dt encoding:NSUTF8StringEncoding];
 completionHandler(NSURLSessionResponseAllow);
 NSLog(@"credintials   %d     \n %@ \n %@ \n %@  ",dataTask.state, body, dataTask, req);
}

5

 -(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask      didReceiveData:(NSData *)data
 {
 NSError *jsonParsingError = nil;

 NSDictionary *urlResponseDataDict = [NSJSONSerialization JSONObjectWithData:data      options:0 error:&jsonParsingError];
 [_savedData appendData:data];

  //  NSString* str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

NSLog(@"did receive data %@",urlResponseDataDict);
}

6

 -(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task      didCompleteWithError:(NSError *)error
 {

 // NSError *jsonParsingError = nil;

 //  NSDictionary *urlResponseDataDict = [NSJSONSerialization JSONObjectWithData:_savedData      options:0 error:&jsonParsingError];

 NSString* str = [[NSString alloc] initWithData:_savedData      encoding:NSUTF8StringEncoding];

 NSLog(@"did complete with error - %@, data - %@, _saveddata - %@", error, str,      _savedData ); //, urlResponseDataDict);
 }

如何通过授权发出简单的数据发布请求 (URLSession:task:task didReceiveChallenge:)? 我做错了什么?

附:对不起我的英语。

【问题讨论】:

  • 不相关但是,1. 在didReceiveChallenge 中,您不必调用[[challenge sender] useCredential...],因为您正在调用完成块。您应该只调用发件人的useCredentialNSURLConnection(或NSURLDownload)。 2. 不要解析didReceiveData 中的响应,只解析appendData。在didCompleteWithError 中进行NSJSONSerialization 解析。如果您的响应足够大,则可能需要多次调用 didReceiveData 才能让应用收到所有数据。
  • 谢谢。我想如果没有你的评论,我不会意识到我在这个地方犯了很长一段时间的大错误......

标签: objective-c post authorization nsurlrequest nsurlsession


【解决方案1】:

问题可能出在 PHP 脚本上:$_post$_POST 不一样(注意大小写)

【讨论】:

  • 谢谢 .... 这很荒谬,但现在可以了 )))。每次我制作一个没有 www-authorization 标头的 php 文件时,我都使用了正确的 $_POST,而每次我使用“www-authorization”时,我都制作了 $_post ....
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-01-17
  • 1970-01-01
  • 2020-02-11
  • 2020-07-17
  • 2011-01-02
  • 2020-01-19
  • 2021-01-09
相关资源
最近更新 更多