发送HTTP POST请求错误

问题描述:

我在正确获取JSON时遇到问题。这是我如何查询数据库。发送HTTP POST请求错误

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]; 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data { 

    NSMutableData *receivedData = [[NSMutableData alloc] init]; 

    [receivedData appendData:data]; 

    NSString *stringr; 

    stringr = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding]; 

    NSLog(@"Get string %@", stringr); 

    NSError *error; 

    NSDictionary *thejson = [NSJSONSerialization JSONObjectWithData:receivedData options:kNilOptions error:&error]; 

    NSLog(@"Get dict %@", thejson); ///THIS RESULTS NULL 
} 

从获取字符串的NSLog我得到两个响应。我解释得更好。如果我在浏览器中输入我的请求URL,我会看到整个JSON响应,而从我的NSLog中,我得到一部分响应,另一部分仍在同一个NSLog中,但比第一个NSLog时间长。

例如:2014年10月11日19:38:58.401 MYAPP [1607:365755]获取字典(在这里我得到我的JSON的第一部分)

2014年10月11日19:38:58.401 Myapp [1607:365755]获取字典(这里我得到我的JSON的第二个也是最后一部分)。

为什么我没有得到一个和整个NSLog回复?我确信我误会了一些东西,但我真的不知道是什么。谢谢。

考虑到可能需要多次调用didReceiveData来处理,你应该从它的解析数据的接收分开:

  1. 创建NSMutableData属性:

    @property (nonatomic, strong) NSMutableData *receivedData; 
    
  2. 在开始连接之前,初始化它:

    self.receivedData = [NSMutableData data]; 
    [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
    
  3. 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); 
    } 
    
  4. 只有尝试分析它:

    - (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 

     }]; 

    } 

如果您使用我的代码,我建议您创建一个协议来接收答案。你有这样的例子在https://github.com/sampayo/just-eat-restaurants这是类RequestHelper.m