iphone学习笔记--使用http与服务器端通信
来源:互联网 发布:php 字符型转变为数值 编辑:程序博客网 时间:2024/05/29 08:43
与服务器端的通信的方式有两种: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看输出结果。
- iphone学习笔记--使用http与服务器端通信
- Android客户端与Web服务器端Http通信
- 【学习笔记】-HTTP通信
- Flex与服务器端通信
- 客户端与服务器端通信
- 网络基础学习笔记一------TCP通信之服务器端
- 网络基础学习笔记二------UDP通信之服务器端
- IPHONE 多线程使用学习笔记
- node.js学习笔记之HTTP---发送服务器端响应流
- Android学习笔记——Http通信
- 学习笔记(一)http通信本质
- 客户端与服务器端的通信
- Sencha Touch -与服务器端通信。
- 客户端与服务器端的通信
- Android使用http协议与服务器通信
- Android使用http协议与服务器通信
- Android使用http协议与服务器通信
- Android使用http协议与服务器通信
- WdatePicker日历控件使用方法
- oracle 启动关闭以及监听启动关闭命令
- 自定义RadioButton
- YUV422 to RGB 转换
- exe4j把jar打包成exe文件,运行报错的解决办法!!!
- iphone学习笔记--使用http与服务器端通信
- usaco3.2kimbits
- mysql绿化
- WIN7上运行PB5.0
- SQL ISNULL ( check_expression , replacement_value )
- 学习Objective-C:入门手册
- android编译系统makefile(Android.mk)写法
- 赏心悦目的宏代码
- 自己写的一个JS表格分页代码第一版