2008-11-26 9 views

Respuesta

8

Si está utilizando Objective C, necesitará utilizar las clases NSURL, NSURLRequest y NURLConnection. Apple's NSURLRequest doc. HttpRequest es para JavaScript.

45

Suponga que su clase tiene una variable responseData ejemplo, entonces:

responseData = [[NSMutableData data] retain]; 

NSURLRequest *request = 
    [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.domain.com/path"]]; 
[[NSURLConnection alloc] initWithRequest:request delegate:self]; 

y luego añadir los métodos siguientes a su clase:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 
    [responseData setLength:0]; 
} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 
    [responseData appendData:data]; 
} 

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{ 
    // Show error 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    // Once this method is invoked, "responseData" contains the complete result 
} 

Esto enviará un GET. En el momento en el último método se llama, responseData contendrá toda la respuesta HTTP (convertir en cadena con [[alloc NSString] initWithData: codificación:].

Alternativamente, para POST, vuelva a colocar el primer bloque de código con:

NSMutableURLRequest *request = 
     [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.domain.com/path"]]; 
[request setHTTPMethod:@"POST"]; 

NSString *postString = @"Some post string"; 
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]]; 
+1

he publicado una pregunta de seguimiento sobre esto aquí: http://stackoverflow.com/questions/431826/making-get-and-post-requests-from-an-iphone-application-clarification-needed (I pensé que era digno de su propia pregunta.) – Greg

+0

Asegúrese de verificar que [[NSURLConnection alloc] initWithRequest: request delegate: self]; llame para obtener un retorno nulo. – Erik

Cuestiones relacionadas