iphone学习笔记--使用http与服务器端通信

与服务器端的通信的方式有两种: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看输出结果。



 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值