AFNetworking 2获得JSON响应

时间:2014-02-04 13:00:33

标签: ios get afnetworking-2

我正在构建一个应该返回JSON对象的简单GET函数。使用AFNetworking 2.代码编译,但我无法确定在运行时获得的错误的来源。 可能是服务器上的内容类型:是text / html,我期待jsonobj。 服务器使用“Basic user:id”标头,我应该将它添加到setValue forHttpHeaderField吗?

    AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:@"http://the website.com"]];
    manager.securityPolicy.allowInvalidCertificates = YES;
    [manager setRequestSerializer:[AFHTTPRequestSerializer serializer]];
    [manager.requestSerializer setAuthorizationHeaderFieldWithUsername:@"user" password:@"pass"];   
    [manager GET:@"/api/data/interval?month" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@" Yep %@", responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@" Nope %@", error);
    }];

这是我得到的错误

 Nope Error Domain=AFNetworkingErrorDomain Code=-1011 "Request failed: forbidden (403)" UserInfo=0x8a9dec0 {NSErrorFailingURLKey=http://thewebsite.com/api/data/interval?month, NSLocalizedDescription=Request failed: forbidden (403), NSUnderlyingError=0x8a99e00 "Request failed: unacceptable content-type: text/html", AFNetworkingOperationFailingURLResponseErrorKey=<NSHTTPURLResponse: 0x8bb0ac0> { URL: http://thewebsite.com/api/data/interval?month } { status code: 403, headers {
    Connection = "keep-alive";
    "Content-Encoding" = gzip;
    "Content-Language" = "";
    "Content-Type" = "text/html";
    Date = "Tue, 04 Feb 2014 13:02:12 GMT";

1 个答案:

答案 0 :(得分:1)

首先,您必须初始化您的基本网址。例如:

 NSURL *baseURL = [NSURL URLWithString:@"www.abv.bg"];

之后,您可以创建相对路径,如:

NSString *path = @"/Path/to/somewhere";

最后是这样的init URL字符串:

NSString *absoluteURL = [[NSURL URLWithString:path relativeToURL:baseURL] absoluteString];

现在您可以执行请求,并且您知道该URL正确无误:

[manager GET:absoluteURL parameters:nil  success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@" Yep %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@" Nope %@", error);
}];

在您的解决方案中,您尝试执行请求以解决@“/ api / data / interval?month”而不是真实URL。 HTH。