Exemple de post http simple en Objective-C?

J'ai une page web php qui nécessite un login (identifiant et mot de passe). J'ai l'user entrer l'information dans l'application très bien .. mais j'ai besoin d'un exemple sur la façon de faire une request POST à ​​un site Web. L'exemple de la pomme sur le site de support est plutôt compliqué montrant un téléchargement de photo .. le mien devrait être plus simple .. Je veux juste postr 2 lignes de text .. N'importe qui a de bons exemples?

Alex

Que diriez-vous

NSSsortingng *post = @"key1=val1&key2=val2"; NSData *postData = [post dataUsingEncoding:NSASCIISsortingngEncoding allowLossyConversion:YES]; NSSsortingng *postLength = [NSSsortingng ssortingngWithFormat:@"%d", [postData length]]; NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; [request setURL:[NSURL URLWithSsortingng:@"http://www.nowhere.com/sendFormHere.php"]]; [request setHTTPMethod:@"POST"]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; [request setHTTPBody:postData]; 

Extrait de http://deusty.blogspot.com/2006/11/sending-http-get-and-post-from-cocoa.html . C'est ce que j'ai récemment utilisé, et cela a bien fonctionné pour moi.

Btw, 5 secondes de googling aurait laissé le même résultat, en utilisant les termes "post request de cacao";)

Du site officiel d'Apple :

 // In body data for the 'application/x-www-form-urlencoded' content type, // form fields are separated by an ampersand. Note the absence of a // leading ampersand. NSSsortingng *bodyData = @"name=Jane+Doe&address=123+Main+St"; NSMutableURLRequest *postRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithSsortingng:@"https://www.apple.com"]]; // Set the request's content type to application/x-www-form-urlencoded [postRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; // Designate the request a POST request and specify its body data [postRequest setHTTPMethod:@"POST"]; [postRequest setHTTPBody:[NSData dataWithBytes:[bodyData UTF8Ssortingng] length:strlen([bodyData UTF8Ssortingng])]]; // Initialize the NSURLConnection and proceed as described in // Resortingeving the Contents of a URL 

De: code avec chris

  // Create the request. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithSsortingng:@"http://google.com"]]; // Specify that it will be a POST request request.HTTPMethod = @"POST"; // This is how we set header fields [request setValue:@"application/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"]; // Convert your data and set your request's HTTPBody property NSSsortingng *ssortingngData = @"some data"; NSData *requestBodyData = [ssortingngData dataUsingEncoding:NSUTF8SsortingngEncoding]; request.HTTPBody = requestBodyData; // Create url connection and fire request NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 

ASIHTTPRequest rend la communication réseau vraiment facile

 ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url]; [request addPostValue:@"Ben" forKey:@"names"]; [request addPostValue:@"George" forKey:@"names"]; [request addFile:@"/Users/ben/Desktop/ben.jpg" forKey:@"photos"]; [request addData:imageData withFileName:@"george.jpg" andContentType:@"image/jpeg" forKey:@"photos"]; 

Vous pouvez faire en utilisant deux options:

Utilisation de NSURLConnection:

 NSURL* URL = [NSURL URLWithSsortingng:@"http://www.example.com/path"]; NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:URL]; request.HTTPMethod = @"POST"; // Form URL-Encoded Body NSDictionary* bodyParameters = @{ @"username": @"reallyrambody", @"password": @"123456" }; request.HTTPBody = [NSSsortingngFromQueryParameters(bodyParameters) dataUsingEncoding:NSUTF8SsortingngEncoding]; // Connection NSURLConnection* connection = [NSURLConnection connectionWithRequest:request delegate:nil]; [connection start]; /* * Utils: Add this section before your class implementation */ /** This creates a new query parameters ssortingng from the given NSDictionary. For example, if the input is @{@"day":@"Tuesday", @"month":@"January"}, the output ssortingng will be @"day=Tuesday&month=January". @param queryParameters The input dictionary. @return The created parameters ssortingng. */ static NSSsortingng* NSSsortingngFromQueryParameters(NSDictionary* queryParameters) { NSMutableArray* parts = [NSMutableArray array]; [queryParameters enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) { NSSsortingng *part = [NSSsortingng ssortingngWithFormat: @"%@=%@", [key ssortingngByAddingPercentEscapesUsingEncoding: NSUTF8SsortingngEncoding], [value ssortingngByAddingPercentEscapesUsingEncoding: NSUTF8SsortingngEncoding] ]; [parts addObject:part]; }]; return [parts componentsJoinedBySsortingng: @"&"]; } /** Creates a new URL by adding the given query parameters. @param URL The input URL. @param queryParameters The query parameter dictionary to add. @return A new NSURL. */ static NSURL* NSURLByAppendingQueryParameters(NSURL* URL, NSDictionary* queryParameters) { NSSsortingng* URLSsortingng = [NSSsortingng ssortingngWithFormat:@"%@?%@", [URL absoluteSsortingng], NSSsortingngFromQueryParameters(queryParameters) ]; return [NSURL URLWithSsortingng:URLSsortingng]; } 

Utiliser NSURLSession

 - (void)sendRequest:(id)sender { /* Configure session, choose between: * defaultSessionConfiguration * ephemeralSessionConfiguration * backgroundSessionConfigurationWithIdentifier: And set session-wide properties, such as: HTTPAdditionalHeaders, HTTPCookieAcceptPolicy, requestCachePolicy or timeoutIntervalForRequest. */ NSURLSessionConfiguration* sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration]; /* Create session, and optionally set a NSURLSessionDelegate. */ NSURLSession* session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:nil delegateQueue:nil]; /* Create the Request: Token Duplicate (POST http://www.example.com/path) */ NSURL* URL = [NSURL URLWithSsortingng:@"http://www.example.com/path"]; NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:URL]; request.HTTPMethod = @"POST"; // Form URL-Encoded Body NSDictionary* bodyParameters = @{ @"username": @"reallyram", @"password": @"123456" }; request.HTTPBody = [NSSsortingngFromQueryParameters(bodyParameters) dataUsingEncoding:NSUTF8SsortingngEncoding]; /* Start a new Task */ NSURLSessionDataTask* task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if (error == nil) { // Success NSLog(@"URL Session Task Succeeded: HTTP %ld", ((NSHTTPURLResponse*)response).statusCode); } else { // Failure NSLog(@"URL Session Task Failed: %@", [error localizedDescription]); } }]; [task resume]; } /* * Utils: Add this section before your class implementation */ /** This creates a new query parameters ssortingng from the given NSDictionary. For example, if the input is @{@"day":@"Tuesday", @"month":@"January"}, the output ssortingng will be @"day=Tuesday&month=January". @param queryParameters The input dictionary. @return The created parameters ssortingng. */ static NSSsortingng* NSSsortingngFromQueryParameters(NSDictionary* queryParameters) { NSMutableArray* parts = [NSMutableArray array]; [queryParameters enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) { NSSsortingng *part = [NSSsortingng ssortingngWithFormat: @"%@=%@", [key ssortingngByAddingPercentEscapesUsingEncoding: NSUTF8SsortingngEncoding], [value ssortingngByAddingPercentEscapesUsingEncoding: NSUTF8SsortingngEncoding] ]; [parts addObject:part]; }]; return [parts componentsJoinedBySsortingng: @"&"]; } /** Creates a new URL by adding the given query parameters. @param URL The input URL. @param queryParameters The query parameter dictionary to add. @return A new NSURL. */ static NSURL* NSURLByAppendingQueryParameters(NSURL* URL, NSDictionary* queryParameters) { NSSsortingng* URLSsortingng = [NSSsortingng ssortingngWithFormat:@"%@?%@", [URL absoluteSsortingng], NSSsortingngFromQueryParameters(queryParameters) ]; return [NSURL URLWithSsortingng:URLSsortingng]; } 

Je suis un débutant dans les applications iPhone et j'ai toujours un problème même si j'ai suivi les conseils ci-dessus. Il semble que les variables POST ne sont pas reçues par mon server – je ne sais pas si elles proviennent de php ou d'un code objective-c …

la partie objective-c (codée suivant la méthode du protocole de Chris)

 // Create the request. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithSsortingng:@"http://example.php"]]; // Specify that it will be a POST request request.HTTPMethod = @"POST"; // This is how we set header fields [request setValue:@"application/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"]; // Convert your data and set your request's HTTPBody property NSSsortingng *ssortingngData = [NSSsortingng ssortingngWithFormat:@"user_name=%@&password=%@", self.userNameField.text , self.passwordTextField.text]; NSData *requestBodyData = [ssortingngData dataUsingEncoding:NSUTF8SsortingngEncoding]; request.HTTPBody = requestBodyData; // Create url connection and fire request //NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self]; NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; NSLog(@"Response: %@",[[NSSsortingng alloc] initWithData:response encoding:NSUTF8SsortingngEncoding]); 

Ci-dessous la partie php:

 if (isset($_POST['user_name'],$_POST['password'])) { // Create connection $con2=mysqli_connect($servername, $username, $password, $dbname); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } else { // resortingeve POST vars $username = $_POST['user_name']; $password = $_POST['password']; $sql = "INSERT INTO myTable (user_name, password) VALUES ('$username', '$password')"; $retval = mysqli_query( $sql, $con2 ); if(! $retval ) { die('Could not enter data: ' . mysql_error()); } echo "Entered data successfully\n"; mysqli_close($con2); } } else { echo "No data input in php"; } 

J'ai été coincé les derniers jours sur celui-ci.

  NSMutableDictionary *contentDictionary = [[NSMutableDictionary alloc]init]; [contentDictionary setValue:@"name" forKey:@"email"]; [contentDictionary setValue:@"name" forKey:@"username"]; [contentDictionary setValue:@"name" forKey:@"password"]; [contentDictionary setValue:@"name" forKey:@"firstName"]; [contentDictionary setValue:@"name" forKey:@"lastName"]; NSData *data = [NSJSONSerialization dataWithJSONObject:contentDictionary options:NSJSONWritingPrettyPrinted error:nil]; NSSsortingng *jsonStr = [[NSSsortingng alloc] initWithData:data encoding:NSUTF8SsortingngEncoding]; NSLog(@"%@",jsonStr); NSSsortingng *urlSsortingng = [NSSsortingng ssortingngWithFormat:@"http://testgcride.com:8081/v1/users"]; NSURL *url = [NSURL URLWithSsortingng:urlSsortingng]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request setHTTPMethod:@"POST"]; [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; [request setHTTPBody:[jsonStr dataUsingEncoding:NSUTF8SsortingngEncoding]]; AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; [manager.requestSerializer setAuthorizationHeaderFieldWithUsername:@"lessam" password:@"cheese"]; manager.requestSerializer = [AFJSONRequestSerializer serializer]; AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request success:<block> failure:<block>]; 

Merci beaucoup ça a marché, merci de noter que j'ai fait une faute de frappe en php comme cela devrait être mysqli_query ($ con2, $ sql)

Ici j'ajoute l'exemple de code pour la réponse d'printing de post de HTTP et l'parsing comme JSON si possible, il traitera tout async ainsi votre interface graphique sera rafraîchissante juste et ne gèlera pas du tout – ce qui est important de remarquer.

 //POST DATA NSSsortingng *theBody = [NSSsortingng ssortingngWithFormat:@"parameter=%@",YOUR_VAR_HERE]; NSData *bodyData = [theBody dataUsingEncoding:NSASCIISsortingngEncoding allowLossyConversion:YES]; //URL CONFIG NSSsortingng *serverURL = @"https://your-website-here.com"; NSSsortingng *downloadUrl = [NSSsortingng ssortingngWithFormat:@"%@/your-friendly-url-here/json",serverURL]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithSsortingng: downloadUrl]]; //POST DATA SETUP [request setHTTPMethod:@"POST"]; [request setHTTPBody:bodyData]; //DEBUG MESSAGE NSLog(@"Trying to call ws %@",downloadUrl); //EXEC CALL [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { if (error) { NSLog(@"Download Error:%@",error.description); } if (data) { // // THIS CODE IS FOR PRINTING THE RESPONSE // NSSsortingng *returnSsortingng = [[NSSsortingng alloc] initWithData:data encoding: NSUTF8SsortingngEncoding]; NSLog(@"Response:%@",returnSsortingng); //PARSE JSON RESPONSE NSDictionary *json_response = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL]; if ( json_response ) { if ( [json_response isKindOfClass:[NSDictionary class]] ) { // do dictionary things for ( NSSsortingng *key in [json_response allKeys] ) { NSLog(@"%@: %@", key, json_response[key]); } } else if ( [json_response isKindOfClass:[NSArray class]] ) { NSLog(@"%@",json_response); } } else { NSLog(@"Error serializing JSON: %@", error); NSLog(@"RAW RESPONSE: %@",data); NSSsortingng *returnSsortingng2 = [[NSSsortingng alloc] initWithData:data encoding: NSUTF8SsortingngEncoding]; NSLog(@"Response:%@",returnSsortingng2); } } }]; 

J'espère que cela t'aides!