2014-10-09 38 views
1

目標C代碼爲什麼我會收到來自該請求的iOS JSON

@try { 
     NSURL *postURL = [NSURL URLWithString: @"http://yyy.com/api/Customer/"]; 
     NSDictionary *myDic = [[NSDictionary alloc] initWithObjectsAndKeys: 
           self.firstNameTextField.text, CustFirstName, 
           self.lastNameTextField.text, CustLastName, 
           nil]; 

     NSError *error; 

     NSData *jsonData = [NSJSONSerialization dataWithJSONObject:myDic options:NSJSONWritingPrettyPrinted error:&error]; 

     if (!jsonData) { 
      NSLog(@"Got an error: %@", error); 
     } else { 

      // Get our Access Token back 
      NSString *savedToken = [[NSUserDefaults standardUserDefaults] 
            stringForKey:@"savedToken"]; 
      NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
      [request setURL:postURL]; 
      [request setHTTPMethod: @"POST"]; 
      [request setValue: @"application/json" forHTTPHeaderField: @"Accept"]; 
      [request setValue: @"application/json; charset=utf-8" forHTTPHeaderField: @"content-type"]; 
      [request setValue:savedToken forHTTPHeaderField:@"Authorization"]; 
      [request setHTTPBody:jsonData]; 

      NSHTTPURLResponse *response = nil; 

      NSLog(@"Response code: %ld", (long)[response statusCode]); 

      //NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 
      if ([response statusCode] >= 200 && [response statusCode] < 300) 
      { 
       NSLog(@"Saving Success!"); 
       [self performSegueWithIdentifier:@"edit_add_customer" sender:self]; 
      } else { 
       NSLog(@"Saving Fail!"); 
       [self alertStatus:@"Please try again" :@"Saving Fail" :0]; 
      } 


     } 
} 
@catch (NSException *exception) { 
    NSLog(@"Exception: %@", exception); 
    [self alertStatus:@"Error Retrieving Customer Data." :@"Error!" :0]; 
} 

反正我的JSON字符串是正確的,正如我在休息客戶所空響應。它能夠保存。 我嘗試記錄我的響應StatusCode,它顯示爲'0'。有人可以幫我弄這個嗎?

+0

你想念的連接請求後檢查的StatusCode:NSURLConnection的*連接= [[NSURLConnection的alloc] initWithRequest:request delegate:self]; ? – Horst 2014-10-09 08:33:35

回答

0

你特林你做實際的請求之前得到的StatusCode

NSLog(@"Response code: %ld", (long)[response statusCode]); 
    NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 

你有

NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 
    NSLog(@"Response code: %ld", (long)[response statusCode]); 
+0

嗨,很抱歉,遲到了。是的,我猜你的代碼正在使它工作,但我現在收到500響應而不是空響應。仍然試圖想像Rest客戶端工作時我的代碼有什麼問題。 – specialone 2014-10-10 13:09:45

+0

HTTP錯誤500「內部服務器錯誤」。服務器無法執行某些操作。嘗試在模擬器中「重置內容和設置」。可能你會得到相同的,然後在你的手機上。 – kabarga 2014-10-10 13:22:01

+0

謝謝你很棒。哇,這有效。這很奇怪,現在我可以成功地發佈數據。爲什麼這樣? – specialone 2014-10-10 13:27:20

相關問題