2012-06-01 11 views
5

Sto lavorando a un metodo per centralizzare le mie connessioni URL per l'invio e la ricezione di dati JSON da un server. Funziona con il POST, ma non GET. Sto utilizzando un server di Google App Engine e sul mio computer gestirà le richieste POST e restituirò i risultati corretti (e registro in modo appropriato), ma ricevo il seguente errore quando provo la richiesta con un metodo GET:NSURLConnection si chiude presto 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} 

Inoltre, il server di sviluppo GAE mostra un errore "pipe rotto", che indica che il client ha chiuso la connessione prima che il server abbia completato l'invio di tutti i dati.

Ecco il metodo:

/* 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]; 
} 

Una chiamata di esempio potrebbe essere:

NSDictionary *response = [fetcher sendRequestToModule:@"login" ofType:@"GET" function:@"validate_email" params:dict]; 

Ancora una volta, questo funziona con un post, ma non un GET. Come posso risolvere questo?

risposta

2

Penso che la causa principale sia l'URL non valido.

La codifica JSON includerà elementi come '{', '}', '[' e ']'. Tutti questi devono essere codificati tramite URL prima di essere aggiunti a un URL.

NSString *query = [NSString stringWithFormat:@"?action=%@", [str_params JSONString]]; 
query = [query stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 

NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@", str_url, query]]; 

Per rispondere direttamente alla tua domanda:

Secondo CFNetwork Error Codes Reference l'errore è kCFErrorHTTPParseFailure. Ciò significa che il client non è riuscito a analizzare correttamente la risposta HTTP.

+0

cercherò che fuori, grazie! – drodman

1

Il motivo per cui un GET non include un corpo. Perché dovresti comunque inviare JSON in un GET?

Se l'API di destinazione restituisce solo i dati, li si passa nei parametri url.

Se si desidera inviare dati e "ottenere" una risposta, utilizzare un post ed esaminare il corpo al momento del reso.

Campione del messaggio:

NSError *error; 
NSString *urlString = [[NSString alloc] initWithFormat:@"http://%@:%@/XXXX/MVC Controller Method/%@",self.ServerName, self.Port, sessionId ]; 
NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding ]]; 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 
[request setHTTPMethod:@"POST"]; 

// hydrate the remote object 
NSString *returnString = [rdc JSONRepresentation]; 
NSData *s10 = [returnString dataUsingEncoding:NSUTF8StringEncoding]; 
[request setHTTPBody:s10]; 
NSURLResponse *theResponse = [[NSURLResponse alloc] init]; 
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&error]; 
NSString *message = [[NSString alloc] initWithFormat: @"nothing"]; 

if (error) { 
    message = [[NSString alloc] initWithFormat:@"Error: %@", error]; 


} else { 
    message = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 

} 

NSLog(@"%@", message); 

return message; 
8

Nel mio caso non ero chiamando [richiesta setHTTPMethod: @ "POST"]

+0

Non stavo specificando un GET o un POST che mi ha portato a questo errore. Specificare GET ha risolto per me. – njtman