【问题标题】:Trouble getting a 401 response (unauthorized) from an iPhone app无法从 iPhone 应用程序获得 401 响应(未经授权)
【发布时间】:2011-01-07 16:16:12
【问题描述】:

我有一个同步方法来发送如下所示的请求:

+ (NSString *)sendRequest:(NSMutableURLRequest *)request {
    NSHTTPURLResponse *response;
    NSError *error;

    NSData *responseData = 
 [NSURLConnection sendSynchronousRequest:request                         
        returningResponse:&response 
           error:&error];

 NSLog(@"response = %@", response);
 NSLog(@"error = %@", [error localizedDescription]);

    NSString *responseString = 
 [[NSString alloc] initWithData:responseData 
        encoding:NSUTF8StringEncoding];
    [responseString autorelease];

    NSLog(@"%@: %@", [request HTTPMethod], [request URL]);
    NSLog(@"Response Code: %d", [response statusCode]);
    NSLog(@"Content-Type: %@", [[response allHeaderFields] 
                                objectForKey:@"Content-Type"]);
    NSLog(@"Response: %@\n\n", responseString);   

    return responseString;
}

对于特定请求,我收到一个空响应,并显示错误消息“无法完成操作。(NSURLErrorDomain 错误 -1012。)”

根据Foundation constants reference,此代码是 NSURLErrorUserCancelledAuthentication,描述为

异步请求时返回 身份验证被取消 用户。

这通常是通过点击 中的“取消”按钮 用户名/密码对话框,而不是 用户试图 验证。

但是,我没有用户点击取消。我只是在未经授权的情况下请求检索事件列表,因此我返回的 401 应该产生未经授权的响应,而不是带有 NSURLErrorUserCancelledAuthentication 错误的空响应。返回此响应的我的 Rails 代码如下:

def require_auth
    # Return unauthorized if the API call was not made by an authorized user
    unless current_user
      respond_to do |format|
        #format.json { render :text => "Unauthorized", :status => :unauthorized }
        format.json { head :unauthorized }
        format.xml { head :unauthorized }
      end
    end   
end

我的 Rails 日志的输出如下所示:

Started GET "/events.json" for
127.0.0.1 at Fri Jan 07 10:51:47 -0500 2011   
Processing by EventsController#index as JSON Completed 401 Unauthorized in 0ms

有谁知道为什么会发生这种情况以及如何创建正确的响应?

【问题讨论】:

    标签: iphone ruby-on-rails unauthorized nsurlerrordomain


    【解决方案1】:

    我更像一个 Rails 人而不是 iPhone 人,但快速谷歌搜索(参见此处的线程:http://discussions.apple.com/thread.jspa?messageID=7915337)NSURLConnection 仅在成功时返回 NSHTTPURLResponse (200),否则返回空响应和你的行为'在 401 上看到。

    这似乎是 API 的本质,如果您想区分不同的非 200 状态响应,则需要使用较低级别的东西。

    另一个 Stackoverflow 线程似乎暗示 API 的异步版本将让您获得所有响应代码和数据:iOS: How can i receive HTTP 401 instead of -1012 NSURLErrorUserCancelledAuthentication

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-20
      • 2022-08-07
      • 2018-03-25
      • 1970-01-01
      • 2017-06-01
      • 1970-01-01
      • 2020-07-07
      相关资源
      最近更新 更多