2013-03-21 25 views
2

我使用-[NSURLConnection initWithRequest...]連接到服務器, ,當服務器端發生故障時,它將響應正文中帶有消息的錯誤400。 當沒有錯誤時,我可以在didReceiveData中獲取響應數據。但是,當服務器返回錯誤400時,我在didReceiveData中沒有收到任何錯誤消息。當得到錯誤時NSURLConnection不同的結果

但是,如果我使用-[NSURLConnection sendSynchronousRequest...]做相同的請求 我確實從sendSynchronousRequest的返回值得到錯誤數據。

我想從didReceiveData得到錯誤信息,但我不知道爲什麼我不能得到它。 做什麼不同,有人可以幫助我嗎?

這樣我可以得到錯誤信息:

NSURL *url = [NSURL URLWithString:@"http://devapi.xxx.com/v1/debug/error"]; 
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] initWithURL:url 
                   cachePolicy:NSURLRequestUseProtocolCachePolicy 
                  timeoutInterval:240] autorelease]; 

[request setHTTPMethod:@"POST"]; 


[request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; 
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 

NSURLResponse *response = nil; 
NSError *error = nil; 
NSData *data = [NSURLConnection sendSynchronousRequest:request 
            returningResponse:&response 
               error:&error]; 


NSLog(@"STATUS:%d", [((NSHTTPURLResponse *)response) statusCode]); 
NSLog(@"ERROR:%@", error); 

這樣,我不能得到它:

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://devapi.xxx.com/v1/debug/error"] 
                  cachePolicy:NSURLRequestUseProtocolCachePolicy 
                 timeoutInterval:240] autorelease]; 

[request setHTTPMethod:@"POST"]; 


[request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; 
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 
urlConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES]; 

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 
    NSLog(@"statusCode:%d",((NSHTTPURLResponse *)response).statusCode); 
} 

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { 
} 
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 
[receivedData appendData:data]; 
NSLog(@"DATA:%@",[NSString stringWithCString:[receivedData bytes] encoding:NSASCIIStringEncoding]); 
} 
+0

成功(非400)響應調用'didReceiveData'? 'didFailWithError'曾經被調用過嗎? – 2013-03-21 09:15:23

+0

您可以顯示您的日誌輸出的狀態,數據和錯誤? – 2013-03-21 09:18:44

+0

他的問題是,當HTTP代碼不是200時,他不能總是從服務器讀取響應的「內容」部分。這是一個問題,因爲這是寫入哪種應用程序錯誤的地方。 – Vincent 2013-03-21 10:14:26

回答

1

我想我發現了什麼發生是, 當我didReceiveResponse得到一個錯誤狀態代碼, 我立即嘗試獲取數據並取消連接, 但它是錯的, 因爲didReceiveData還在接受在didReceiveResponse之後。

非常感謝!

1

用於處理這些錯誤此委託方法。

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { 
     NSLog(@" Failed with error---%@",error); 
}