【发布时间】: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