与服务器端的通信的方式有两种:1).http 2).socket 3).webservice
下面是在iphone平台上使用http与服务器端通信,费话不说,直接代码。
1. 创建一个基于视图的应用程序,并命名(这里命名为NetDemo),打开NetDemoViewController.h文件,代码如下:
#import <UIKit/UIKit.h>
@interface NetDemoViewController : UIViewController{
UIButton *btn;
NSMutableData *receviedData;
}
@property (nonatomic, retain)IBOutlet UIButton *btn;
@property (nonatomic, retain) NSMutableData *receviedData;
-(IBAction) btnPressed:(id)sender;
@end
修改之后,保存。
2. 打开NetDemoViewController.m文件,代码实现如下:
#import "NetDemoViewController.h"
@implementation NetDemoViewController
@synthesize btn;
@synthesize receviedData;
- (IBAction)btnPressed:(id)sender{
NSString *param = [NSString stringWithFormat:@"action=%@&username=%@&password=%@",@"login",@"netdemo"];
NSData *postData = [param dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:@"http://www.xxx.com/post.php"]];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(conn){
if (receviedData != nil ) {
[receviedData release];
}
receviedData = [[NSMutableData alloc] init];
}
[conn release];
}
#pragma mark -
#pragma mark NSURLConnectionDelegate
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[receviedData appendData:data];
}
- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(@"connection error: %@",[NSMutableString stringWithFormat:@"%@",error]);
}
- (void) connectionDidFinishLoading:(NSURLConnection *)connection{
NSString *result = nil;
@try {
result = [[NSString alloc] initWithBytes:[receviedData bytes] length:[receviedData length] encoding:NSUTF8StringEncoding];
NSLog(@"%@",result);
}
@catch (NSException * e) {
NSLog(@"%@",[NSString stringWithFormat:@"%@",e]);
}
@finally {
[result release];
}
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[receviedData release];
[super dealloc];
}
@end
3. 选中NetDemoViewController.xib文件,双击打开,添加一UIButton控件,绑定到btn输出口,再给Touch up side绑定btnPressed事件,保存退出。
运行程序,正常情况下OK,打开Consle看输出结果。