发送HTTP POST请求错误

时间:2014-10-11 18:12:27

标签: ios objective-c json http-headers

我在正确获取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];

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

从Get string 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回复?我确信我错了什么,但我真的不知道是什么。谢谢。

2 个答案:

答案 0 :(得分:0)

鉴于可能需要多次调用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
    }
    

答案 1 :(得分:0)

我有这个代码。对我来说工作得很好,这是异步的(为了我的更好)。

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