我使用以下代码获取JSON响应但返回的响应为nil,即使打印的数据长度为256
NSString *bodyString = [NSString stringWithFormat:@"{\"method\":\"cargo_shipped\",\"data\":{\"username\":\"%@\",\"shipment_no\":\"70088000071790\"}}",username];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://url..."]];
NSLog(@"url %@",request);
NSData *postData = [bodyString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setHTTPBody:postData];
[request setHTTPMethod:@"POST"];
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSLog(@"above loop");
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
NSLog(@"ENTERED url loop");
if ([data length] > 0 && connectionError == nil)
{
NSLog(@"entered if loop");
[self receivedCargoShippedData:data];
NSString* cargoShippedResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSData *jsonDatas = [cargoShippedResponse dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonDics = [NSJSONSerialization JSONObjectWithData:jsonDatas options:NSJSONReadingAllowFragments error:nil];
NSLog(@"Request %@",bodyString);
NSLog(@"Response %@",jsonDics);
NSLog(@"result: %lu ", (unsigned long)[data length]);
}
else if ([data length] == 0 && connectionError == nil)
{
[self emptyReply];
NSLog(@"empty %@",connectionError);
}
else if (connectionError != nil && connectionError.code == NSURLErrorTimedOut)
{
[self timedOut];
NSLog(@"empty %@",connectionError);
}
else if (connectionError != nil)
{
[self downloadError:connectionError];
NSLog(@"empty %@",connectionError);
} else {
NSLog(@"%@",@"wtf");
}
}];
NSLog(@"finished");
}
代码进入if循环,甚至响应的长度为256.但是,当我尝试获得响应时,它仍为零。
答案 0 :(得分:1)
我自己解决了这个问题:
if ([data length] > 0 && connectionError == nil)
{
NSLog(@"entered if loop");
[self receivedCargoShippedData:data];
NSString* forgotPasswordResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"Request %@",bodyString);
NSLog(@"Response %@",forgotPasswordResponse);
}