下面的代码描述了一个简单的例子POST
方法。(如何传递数据POST
method)
在这里,我描述如何使用 POST 方法。
1.使用实际的用户名和密码设置帖子字符串。
NSString *post = [NSString stringWithFormat:@"Username=%@&Password=%@",@"username",@"password"];
2.使用对帖子字符串进行编码NSASCIIStringEncoding
还有您需要以 NSData 格式发送的帖子字符串。
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
您需要发送数据的实际长度。计算帖子字符串的长度。
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
3.创建一个包含所有属性的 Urlrequest,例如HTTP
方法,带有 post 字符串长度的 http 标头字段。创造URLRequest
对象并初始化它。
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
设置您要向该请求发送数据的 URL。
[request setURL:[NSURL URLWithString:@"http://www.abcde.com/xyz/login.aspx"]];
现在,设置HTTP方法 (发布或获取)。按照代码中的方式编写此行。
[request setHTTPMethod:@"POST"];
Set HTTP
带有帖子数据长度的标头字段。
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
还要设置 HTTP 标头字段的编码值。
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
Set the HTTPBody
带有 postData 的 urlrequest。
[request setHTTPBody:postData];
4.现在,创建 URLConnection 对象。使用 URLRequest 对其进行初始化。
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
它返回初始化的url连接并开始加载url请求的数据。您可以检查一下您是否URL
连接是否正确完成或未使用if/else声明如下。
if(conn) {
NSLog(@"Connection Successful");
} else {
NSLog(@"Connection could not be made");
}
5.要从 HTTP 请求接收数据,您可以使用 URLConnection 类参考提供的委托方法。
委托方法如下。
// This method is used to receive the data which we get using post method.
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data
// This method receives the error report in case of connection is not made to server.
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
// This method is used to process the data after connection has made successfully.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
另请参阅 This http://deusty.blogspot.in/2006/11/sending-http-get-and-post-from-cocoa.html and This http://yuvarajmanickam.wordpress.com/2012/10/17/nsurlconnection-basics-for-ios-beginners/ 文档 for POST
方法。
这是源代码的最佳示例HTTPPost 方法。 https://web.archive.org/web/20150315072521/http://kemal.co/index.php/2012/02/fetching-data-with-getpost-methods-by-using-nsurlconnection/