NSURLConnection在GET早期关闭

dro*_*man 4 json objective-c nsurlconnection

我正在研究一种方法来集中我的URL连接,以便从服务器发送和接收JSON数据.它适用于POST,但不适用于GET.我正在使用Google App Engine服务器,并且在我的计算机上它将处理POST请求并返回正确的结果(并正确记录),但是当我使用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}
Run Code Online (Sandbox Code Playgroud)

此外,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];
}
Run Code Online (Sandbox Code Playgroud)

样本调用将是:

NSDictionary *response = [fetcher sendRequestToModule:@"login" ofType:@"GET" function:@"validate_email" params:dict];
Run Code Online (Sandbox Code Playgroud)

同样,这适用于POST而不是GET.我怎样才能解决这个问题?

小智 8

在我的情况下,我没有调用[request setHTTPMethod:@"POST"]