2

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

+ (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 常量引用,此代码是 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

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

4

1 回答 1

1

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

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

这个其他 Stackoverflow 线程似乎暗示 API 的异步版本将让您获得所有响应代码和数据:iOS:我如何接收 HTTP 401 而不是 -1012 NSURLErrorUserCancelledAuthentication

于 2011-02-21T19:05:57.547 回答