POST 请求未收到全部 json

POST request not receiving all json

一直困扰我的小问题。我一直在向我的 AWS RDB 发出 POST 请求。该请求应该 return 一个 json 输出。我遇到的问题是我会收到返回的字节,但有时它包含不完整的 json,因此无法将其转换为字典。有时我也会收到一个null值的nsdata,但是我可以打印出数据的长度。有任何想法吗?这是我的 iOS 请求代码:

#import "ServiceConnector.h"

@implementation ServiceConnector{
    NSMutableData *receivedData;
}

-(void)getTest{

    //Send to server
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"MY_WEBSITE"]];

   [request setHTTPMethod:@"GET"];

    //initialize an NSURLConnection  with the request
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if(!connection){
        NSLog(@"Connection Failed");
    }

} 

-(void)postTest:(NSMutableArray *)carSearches{

    //build up the request that is to be sent to the server
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"MY_WEBSITE"]];

    [request setHTTPMethod:@"POST"];

    NSError *writeError = nil; 
    NSData *data = [NSJSONSerialization dataWithJSONObject:carSearches options:NSJSONWritingPrettyPrinted error:&writeError];
    NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
    NSLog(@"JSON Output: %@", jsonString);

    [request setHTTPBody:data]; //set the data as the post body
    [request addValue:[NSString stringWithFormat:@"%lu",(unsigned long)data.length] forHTTPHeaderField:@"Content-Length"];

    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if(!connection){
        NSLog(@"Connection Failed");
    }
}

#pragma mark - Data connection delegate -
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ // executed when the connection receives data
    if(!receivedData){
        receivedData = [[NSMutableData alloc]init];
        [receivedData appendData:data];
    }
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{ //executed when the connection fails

    NSLog(@"Connection failed with error: %@",error);
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{

    NSLog(@"Request Complete,recieved %lu bytes of data",(unsigned long)receivedData.length);

    NSString *tmp = [NSString stringWithUTF8String:[receivedData bytes]];
    NSLog(@"%@",tmp);

    NSError *error; 
    NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:[NSData dataWithBytes:[receivedData bytes] length:[receivedData length]] options:NSJSONReadingAllowFragments error:&error];

    [self.delegate requestReturnedData:dictionary];
}

本节中:

if(!receivedData){
    receivedData = [[NSMutableData alloc]init];
    [receivedData appendData:data];
}

如果尚未创建对象,您只是在附加数据。你想每次追加。该 if 语句应如下所示:

if(!receivedData){
    receivedData = [[NSMutableData alloc]init];
}
[receivedData appendData:data];