Ios 发送HTTP POST请求错误

Ios 发送HTTP POST请求错误,ios,objective-c,json,http-headers,Ios,Objective C,Json,Http Headers,我在正确获取JSON时遇到问题。这就是我查询数据库的方式 NSString *url = [NSString stringWithFormat:@"http://www.myURL.com/list?key=%@", myKey] NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL

我在正确获取JSON时遇到问题。这就是我查询数据库的方式

NSString *url = [NSString stringWithFormat:@"http://www.myURL.com/list?key=%@", myKey]

NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
                                initWithURL:[NSURL
                                             URLWithString:url]];

[request setHTTPMethod:@"POST"];
[request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];

NSURLConnection *connection;
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

从Get字符串NSLog中,我得到两个响应。我解释得更好。如果我在浏览器中键入请求URL,我会看到整个JSON响应,而从我的NSLog中,我会得到一部分响应,另一部分仍然在同一个NSLog中,但经过一段时间后,会比第一个NSLog更慢

例如:2014-10-11 19:38:58.401myapp[1607:365755]Get dict(这里我得到了JSON的第一部分)

2014-10-11 19:38:58.401myapp[1607:365755]Get dict(这里是我的JSON的第二部分也是最后一部分)


为什么我没有得到一个完整的NSLog回复?我肯定我弄错了什么,但我真的不知道是什么。谢谢。

鉴于可能需要多次调用
didReceiveData
来处理此问题,您应该将数据的接收与解析分开:

  • 创建
    NSMutableData
    属性:

    @property (nonatomic, strong) NSMutableData *receivedData;
    
  • 启动连接之前,请先对其进行初始化:

    self.receivedData = [NSMutableData data];
    [[NSURLConnection alloc] initWithRequest:request delegate:self];
    
  • receivedData
    中,除了附加数据外,什么也不做:

    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data {
        [self.receivedData appendData:data];
    
        // if you want to log it, you can do:
    
        NSString *stringr = [[NSString alloc] initWithData:self.receivedData encoding:NSASCIIStringEncoding];
        NSLog(@"Get string %@", stringr);
    }
    
  • 仅尝试在以下位置对其进行分析:

    - (void)connectionDidFinishLoading:(NSURLConnection *)connection
    {    
        NSError *error;
    
        NSDictionary *thejson = [NSJSONSerialization JSONObjectWithData:self.receivedData options:kNilOptions error:&error];
    
        NSLog(@"Get dict %@", thejson); ///THIS SHOULD NOT FAIL IF VALID JSON
    }
    

  • 我有这个密码。对我来说,它工作得很好,这是异步的(对我来说更好)

    如果您使用我的代码,我建议您创建一个协议来接收答案。在这门课上有一个例子

    - (void)connectionDidFinishLoading:(NSURLConnection *)connection
    {    
        NSError *error;
    
        NSDictionary *thejson = [NSJSONSerialization JSONObjectWithData:self.receivedData options:kNilOptions error:&error];
    
        NSLog(@"Get dict %@", thejson); ///THIS SHOULD NOT FAIL IF VALID JSON
    }
    
        -(void)preparePostHttpRequestAsynchronous:(NSURL*)urlString
                                            json:(NSMutableDictionary *)jsonDictionary
                                   andIdentifier:(NSInteger)identifier
        {
    
            NSString *newUrlString = [jsonDictionary jsonStringFromDictionary:jsonDictionary ];
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urlString];
            NSString *post = newUrlString;
            NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    
            [request setValue:[NSString stringWithFormat:@"%d", [postData length]] forHTTPHeaderField:@"Content-Length"];
            [request setTimeoutInterval: 20];
            [request setHTTPMethod:@"POST"];
            [request setValue:@"application/json" forHTTPHeaderField:@"Content-type"];
            [request setHTTPBody:postData];
    
            [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *r, NSData *data, NSError *e)
             {
                 NSLog(@"Error %@",e);
    
                 if (e || !data){
                     NSLog (@"Error %@",e);
                     return;
                 }
    
                 NSError *jsonParsingError = nil;
    
                 NSMutableDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:data
                                                                                  options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments|kNilOptions error:&jsonParsingError];
    
                 // here you can do whatever with your data
                 // i recomend you to use a Protocol or something like that
    
             }];
    
        }