2012-02-22 27 views
17

La mayor parte de la información aquí se refiere al proyecto abandonado ASIHTTPREQUEST, así que perdóneme por preguntar nuevamente.Objetivo simple-c Solicitud GET

Efectivamente, tengo que deslizar una banda magnética y enviar la pista 2 de datos a un servicio web que devuelve "registrado" o "notenrolled" (dependiendo del estado de la tarjeta ...)

Así que mis datos viene en simplemente como

NSData *data = [notification object]; 

Y luego tengo que pasar esta a una dirección URL a la orden de

http://example.com/CardSwipe.cfc?method=isenrolled&track2=data

Y a continuación, sólo r eceive una cadena de respuesta ...

He buscado una tonelada y parece haber algunas respuestas contradictorias sobre si esto debería llevarse a cabo simplemente con AFNetworking, RESTkit, o con los protocolos nativos NSURL/NSMutableURLRequest.

Respuesta

51

Las opciones para realizar solicitudes HTTP en Objective-C pueden ser un poco intimidantes. Una solución que me ha funcionado es usar NSMutableURLRequest. Un ejemplo (usando ARC, por lo que tu caso es distinto) es:

- (NSString *) getDataFrom:(NSString *)url{ 
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
    [request setHTTPMethod:@"GET"]; 
    [request setURL:[NSURL URLWithString:url]]; 

    NSError *error = nil; 
    NSHTTPURLResponse *responseCode = nil; 

    NSData *oResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error]; 

    if([responseCode statusCode] != 200){ 
     NSLog(@"Error getting %@, HTTP status code %i", url, [responseCode statusCode]); 
     return nil; 
    } 

    return [[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding]; 
} 

Actualización: título

Su pregunta de, y etiquetado dicen POST, pero su URL de ejemplo podría indicar una petición GET. En el caso de una solicitud GET, el ejemplo anterior es suficiente. Para un puesto, que le cambie la siguiente manera:

- (NSString *) getDataFrom:(NSString *)url withBody:(NSData *)body{ 
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
    [request setHTTPMethod:@"POST"]; 
    [request setHTTPBody:body]; 
    [request setValue:[NSString stringWithFormat:@"%d", [body length]] forHTTPHeaderField:@"Content-Length"]; 
    [request setURL:[NSURL URLWithString:url]]; 

    /* the same as above from here out */ 
} 
+0

OK cool gracias por la respuesta rápida. Estoy un poco confundido acerca de cómo exactamente esto pasa datos? ¿Parece una función simplemente conectarse a un servicio http? –

+1

La muestra POST pasa datos a través de la línea '[request setHTTPBody: body]' y llega al cuerpo HTTP. El ejemplo GET pasaría datos en la URL, por lo que tendrías que formatear tu URL antes de tiempo ... quizás usando '[NSString stringWithFormat: @" http://example.com?param1=%@¶m2=%@ ", param1, param2]'. –

+0

Así que esto está volviendo "

matriculado" al NSLog que es la misma que la fuente de la página. Sin embargo, la página real está enviando Inscrito. Supongo que es una diferencia trivial en el sentido de que podría analizar todo lo demás, pero ¿este código devuelve los datos de la página en lugar de la salida correcta? –

8

Actualización para iOS 9: Así, [NSURLConnection sendSynchronousRequest] es obsoleto a partir de iOS 9. Así es como hacer una petición GET usando NSURLSession partir de IOS 9

solicitud GET

// making a GET request to /init 
NSString *targetUrl = [NSString stringWithFormat:@"%@/init", baseUrl]; 
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
[request setHTTPMethod:@"GET"]; 
[request setURL:[NSURL URLWithString:targetUrl]]; 

[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler: 
    ^(NSData * _Nullable data, 
    NSURLResponse * _Nullable response, 
    NSError * _Nullable error) { 

     NSString *myString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
     NSLog(@"Data received: %@", myString); 
}] resume]; 

solicitud POST

// making a POST request to /init 
NSString *targetUrl = [NSString stringWithFormat:@"%@/init", baseUrl]; 
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 

//Make an NSDictionary that would be converted to an NSData object sent over as JSON with the request body 
NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys: 
        @"basic_attribution", @"scenario_type", 
        nil]; 
NSError *error; 
NSData *postData = [NSJSONSerialization dataWithJSONObject:tmp options:0 error:&error]; 

[request setHTTPBody:postData]; 
[request setHTTPMethod:@"POST"]; 
[request setURL:[NSURL URLWithString:targetUrl]]; 

[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler: 
    ^(NSData * _Nullable data, 
    NSURLResponse * _Nullable response, 
    NSError * _Nullable error) { 

     NSString *responseStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
     NSLog(@"Data received: %@", responseStr); 
}] resume]; 
0
**Simply Call and get your JSON Data.** 

-(void)getJSONData 
{ 

NSURL *url = [NSURL URLWithString:@"http://itunes.apple.com/us/rss/topaudiobooks/limit=10/json"]; 

NSURLSession *session = [NSURLSession sharedSession]; 

NSURLSessionDataTask *data = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { 

    NSError *erro = nil; 

    if (data!=nil) { 

     NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&erro ]; 

     if (json.count > 0) { 

      for(int i = 0; i<10 ; i++){ 

       [arr addObject:[[[json[@"feed"][@"entry"] objectAtIndex:i]valueForKeyPath:@"im:image"] objectAtIndex:0][@"label"]]; 
      } 

     } 
    } 
    dispatch_sync(dispatch_get_main_queue(),^{ 

     [table reloadData]; 
    }); 
}]; 

[data resume]; 
} 
Cuestiones relacionadas