iPhone http Post数据

之前有篇博文介绍从服务器下载数据,再写一篇基于HTTP协议向服务器发送数据的。

这里介绍两种方式,一种用于发送普通数据,一种用于发送xml文件。

这两种方式的区别不大,主要就是NSMutableURLRequest中几个属性的设置。

1、NSMutableURLRequest发送普通数据

NSString *postString = [NSString stringWithFormat:@"name=%@&password=%@",nameFiled.text,passFiled.text];
//将post数据转换为 NSASCIIStringEncoding 编码格式
NSData *postData = [postString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];   
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];  
	
[request setURL:[NSURL URLWithString:@"http://www.wxxf.com/client/login.action"]];
[request setHTTPMethod:@"POST"];   
[request setHTTPBody:postData];

服务器端代码:

<%
String name = request.getParameter("name");
System.out.println("name="+name);
%>

2、NSMutableURLRequest发送xml

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; 
[request setURL:[NSURL URLWithString:@"http://www.wxxf.com/client/login.action"]]; 
[request setHTTPMethod:@"POST"]; 
[request addValue:@"text/xml" forHTTPHeaderField: @"Content-Type"]; 
	
//xml内容
NSMutableData *postBody = [NSMutableData data]; 
[postBody appendData:[[NSString stringWithFormat:@"<Request  Action=\"Login\">"] dataUsingEncoding:NSUTF8StringEncoding]]; 
[postBody appendData:[[NSString stringWithFormat:@"<Body>"] dataUsingEncoding:NSUTF8StringEncoding]]; 
[postBody appendData:[[NSString stringWithFormat:@"<Username>wangjun</Username>"] dataUsingEncoding:NSUTF8StringEncoding]]; 
[postBody appendData:[[NSString stringWithFormat:@"<Password>password</Password>"] dataUsingEncoding:NSUTF8StringEncoding]]; 
[postBody appendData:[[NSString stringWithFormat:@"<PlatformID>2</PlatformID>"] dataUsingEncoding:NSUTF8StringEncoding]]; 
[postBody appendData:[[NSString stringWithFormat:@"</Body>"] dataUsingEncoding:NSUTF8StringEncoding]]; 
[postBody appendData:[[NSString stringWithFormat:@"</Request>"] dataUsingEncoding:NSUTF8StringEncoding]]; 
[request setHTTPBody:postBody]; 
上面的代码创建了请求,可以使用同步或异步的方式发送请求

同步方式:

NSHTTPURLResponse* urlResponse = nil;  
NSError *error = [[NSError alloc] init];  
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];  
异步方式:
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
异步方式的返回数据由代理负责处理。

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值