2014-10-11 221 views
0

我在正確獲取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回覆?我確信我誤會了一些東西,但我真的不知道是什麼。謝謝。

回答

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