我正在研究一種方法來集中我的URL連接以從服務器發送和接收JSON數據。它適用於POST,但不適用於GET。我正在使用Google App Engine服務器,並在我的計算機上處理POST請求並返回正確的結果(並且適當地記錄日誌),但是當我使用GET方法嘗試請求時遇到以下錯誤:NSURLConnection早關閉GET
Error Domain=kCFErrorDomainCFNetwork Code=303 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error 303.)" UserInfo=0xd57e400 {NSErrorFailingURLKey=http://localhost:8080/api/login, NSErrorFailingURLStringKey=http://localhost:8080/api/login}
此外,GAE dev服務器顯示「斷開管道」錯誤,指示客戶端在服務器完成發送所有數據之前關閉連接。
這裏的方法:
/* Connects to a given URL and sends JSON data via HTTP request and returns the result of the request as a dict */
- (id) sendRequestToModule:(NSString*) module ofType:(NSString*) type function:(NSString*) func params:(NSDictionary*) params {
NSString *str_params = [NSDictionary dictionaryWithObjectsAndKeys:func, @"function", params, @"params", nil];
NSString *str_url = [NSString stringWithFormat:@"%@%@", lds_url, module];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:str_url]];
NSData *data = [[NSString stringWithFormat:@"action=%@", [str_params JSONString]] dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:type];
[request setHTTPBody:data];
[request setValue:[NSString stringWithFormat:@"%d", [data length]] forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
NSError *error = nil;
NSURLResponse *response = nil;
NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(@"Error: %@", error);
NSLog(@"Result: %@", [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding]);
return [result objectFromJSONData];
}
示例調用將是:
NSDictionary *response = [fetcher sendRequestToModule:@"login" ofType:@"GET" function:@"validate_email" params:dict];
再次,這可與一個POST而不是GET。我怎樣才能解決這個問題?
我會嘗試了這一點,謝謝! – drodman