我有一个同步方法来发送如下所示的请求:
+ (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
有谁知道为什么会发生这种情况以及如何创建正确的响应?