在Objective-C中简单的http后例子?

我有一个PHP网页,需要login(用户名和密码)。 我有用户input的信息到应用程序就好了..但我需要一个例子如何做一个网站的POST请求。 在支持网站上的苹果示例是相当复杂的显示图片上传..我应该更简单..我只是想发布2行文字..任何人有任何好的例子?

亚历克斯

怎么样

NSString *post = @"key1=val1&key2=val2"; NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]]; NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; [request setURL:[NSURL URLWithString:@"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]; 

取自http://deusty.blogspot.com/2006/11/sending-http-get-and-post-from-cocoa.html 。 这就是我最近使用的,它对我的​​工作很好。

顺便说一句,5秒钟的谷歌search将让相同的结果,使用术语“后请求cocoa”;)

从苹果官方网站 :

 // 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. NSString *bodyData = @"name=Jane+Doe&address=123+Main+St"; NSMutableURLRequest *postRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"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 UTF8String] length:strlen([bodyData UTF8String])]]; // Initialize the NSURLConnection and proceed as described in // Retrieving the Contents of a URL 

来自: 与克里斯的代码

  // Create the request. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"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 NSString *stringData = @"some data"; NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding]; request.HTTPBody = requestBodyData; // Create url connection and fire request NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 

ASIHTTPRequest使networking通信变得非常简单

 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"]; 

你可以使用两个选项:

使用NSURLConnection:

 NSURL* URL = [NSURL URLWithString:@"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 = [NSStringFromQueryParameters(bodyParameters) dataUsingEncoding:NSUTF8StringEncoding]; // Connection NSURLConnection* connection = [NSURLConnection connectionWithRequest:request delegate:nil]; [connection start]; /* * Utils: Add this section before your class implementation */ /** This creates a new query parameters string from the given NSDictionary. For example, if the input is @{@"day":@"Tuesday", @"month":@"January"}, the output string will be @"day=Tuesday&month=January". @param queryParameters The input dictionary. @return The created parameters string. */ static NSString* NSStringFromQueryParameters(NSDictionary* queryParameters) { NSMutableArray* parts = [NSMutableArray array]; [queryParameters enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) { NSString *part = [NSString stringWithFormat: @"%@=%@", [key stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding], [value stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding] ]; [parts addObject:part]; }]; return [parts componentsJoinedByString: @"&"]; } /** 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) { NSString* URLString = [NSString stringWithFormat:@"%@?%@", [URL absoluteString], NSStringFromQueryParameters(queryParameters) ]; return [NSURL URLWithString:URLString]; } 

使用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 URLWithString:@"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 = [NSStringFromQueryParameters(bodyParameters) dataUsingEncoding:NSUTF8StringEncoding]; /* 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 string from the given NSDictionary. For example, if the input is @{@"day":@"Tuesday", @"month":@"January"}, the output string will be @"day=Tuesday&month=January". @param queryParameters The input dictionary. @return The created parameters string. */ static NSString* NSStringFromQueryParameters(NSDictionary* queryParameters) { NSMutableArray* parts = [NSMutableArray array]; [queryParameters enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) { NSString *part = [NSString stringWithFormat: @"%@=%@", [key stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding], [value stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding] ]; [parts addObject:part]; }]; return [parts componentsJoinedByString: @"&"]; } /** 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) { NSString* URLString = [NSString stringWithFormat:@"%@?%@", [URL absoluteString], NSStringFromQueryParameters(queryParameters) ]; return [NSURL URLWithString:URLString]; } 

我是iPhone应用程序的初学者,尽pipe我遵循了上述build议,但仍然遇到了一些问题。 它看起来像POSTvariables不被我的服务器接收 – 不知道如果它来自PHP或Objective-C的代码…

Objective-C部分(按照Chris的协议方法进行编码)

 // Create the request. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"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 NSString *stringData = [NSString stringWithFormat:@"user_name=%@&password=%@", self.userNameField.text , self.passwordTextField.text]; NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding]; 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: %@",[[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]); 

在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 { // retrieve 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"; } 

我一直被困在这一个最后的日子。

  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]; NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@",jsonStr); NSString *urlString = [NSString stringWithFormat:@"http://testgcride.com:8081/v1/users"]; NSURL *url = [NSURL URLWithString:urlString]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request setHTTPMethod:@"POST"]; [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; [request setHTTPBody:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]]; AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; [manager.requestSerializer setAuthorizationHeaderFieldWithUsername:@"moinsam" password:@"cheese"]; manager.requestSerializer = [AFJSONRequestSerializer serializer]; AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request success:<block> failure:<block>]; 

感谢它的工作,请注意我做了一个错误的PHP,因为它应该是mysqli_query($ con2,$ sql)

在这里,我添加了http post打印响应的示例代码,如果可能的话parsing为JSON,它将处理一切asynchronous,所以你的GUI将刷新就好了,不会冻结 – 这一点很重要。

 //POST DATA NSString *theBody = [NSString stringWithFormat:@"parameter=%@",YOUR_VAR_HERE]; NSData *bodyData = [theBody dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; //URL CONFIG NSString *serverURL = @"https://your-website-here.com"; NSString *downloadUrl = [NSString stringWithFormat:@"%@/your-friendly-url-here/json",serverURL]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: 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 // NSString *returnString = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding]; NSLog(@"Response:%@",returnString); //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 ( NSString *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); NSString *returnString2 = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding]; NSLog(@"Response:%@",returnString2); } } }]; 

希望这可以帮助!