我很难尝试从NSURLConnection
请求接收JSON。任何人都可以提供任何建议吗?我无法理解为什么JSON没有出现
编辑:当我将端点/书籍附加到url字符串的末尾时,我得到了这个JSON响应:“json NSDictionary * 0键/值对。”这是否意味着服务器中没有任何内容?
-(void)makeLibraryRequests
{
NSURL *url = [NSURL URLWithString:@"http://prolific-interview.herokuapp.com/54bexxxxxxxxxxxxxxxxaa56"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; //;]cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20.0f];
[request setHTTPMethod:@"GET"];
// This is actually how jQuery works. If you don't tell it what to do with the result, it uses the Content-type to detect what to do with it.
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
//[request setValue:@"application/json; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//parse data here!!
NSError *jsonError;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
if (json) {
//NSArray *allBooks = [json objectForKey:@"books"];
//create your MutableArray here
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
}
else{
NSLog(@"error occured %@", jsonError);
NSString *serverResponse = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(@"\n\nError:\n%@\n\nServer Response:\n%@\n\nCrash:", jsonError.description, serverResponse);
//[NSException raise:@"Invalid Data" format:@"Unable to process web server response."];
}
}];
}
答案 0 :(得分:1)
正如YiPing所指出的,您必须提供books
终点。但是在你第一次发书之前,你不会有任何东西。
NSDictionary *params = @{@"author": @"Diego Torres Milano",
@"categories" : @"android,testing",
@"title": @"Android Application Testing Guide",
@"publisher": @"Packt Publishing",
@"lastCheckedOutBy": @"Joe"};
NSURL *url = [NSURL URLWithString:@"http://prolific-interview.herokuapp.com/54bexxxxxxxxxxxxxaa56/books/"]; // your id removed for security's sake ... put it back in
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
NSError *encodeError;
NSData *body = [NSJSONSerialization dataWithJSONObject:params options:0 error:&encodeError];
NSAssert(body, @"JSON encode failed: %@", encodeError);
request.HTTPBody = body;
因此,首先POST
使用上述请求的书籍,然后您的原始GET
(假设您添加结束点)现在将返回结果。
答案 1 :(得分:0)