iPhone http Post数据

本文介绍了使用HTTP协议通过代码发送普通数据和XML文件至服务器的方法,包括设置请求参数、头信息及处理同步/异步请求。详细展示了两种数据类型在服务器端的解析过程。

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

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

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

1、NSMutableURLRequest发送普通数据

  1. NSString *postString = [NSString stringWithFormat:@"name=%@&password=%@",nameFiled.text,passFiled.text];
  2. //将post数据转换为 NSASCIIStringEncoding 编码格式
  3. NSData *postData = [postString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
  4. NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];

  5. [request setURL:[NSURL URLWithString:@"http://www.wxxf.com/client/login.action"]];
  6. [request setHTTPMethod:@"POST"];
  7. [request setHTTPBody:postData];

服务器端代码:

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

2、NSMutableURLRequest发送xml

  1. NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
  2. [request setURL:[NSURL URLWithString:@"http://www.wxxf.com/client/login.action"]];
  3. [request setHTTPMethod:@"POST"];
  4. [request addValue:@"text/xml" forHTTPHeaderField: @"Content-Type"];

  5. //xml内容
  6. NSMutableData *postBody = [NSMutableData data];
  7. [postBody appendData:[[NSString stringWithFormat:@"<Request Action=\"Login\">"] dataUsingEncoding:NSUTF8StringEncoding]];
  8. [postBody appendData:[[NSString stringWithFormat:@"<Body>"] dataUsingEncoding:NSUTF8StringEncoding]];
  9. [postBody appendData:[[NSString stringWithFormat:@"<Username>wangjun</Username>"] dataUsingEncoding:NSUTF8StringEncoding]];
  10. [postBody appendData:[[NSString stringWithFormat:@"<Password>password</Password>"] dataUsingEncoding:NSUTF8StringEncoding]];
  11. [postBody appendData:[[NSString stringWithFormat:@"<PlatformID>2</PlatformID>"] dataUsingEncoding:NSUTF8StringEncoding]];
  12. [postBody appendData:[[NSString stringWithFormat:@"</Body>"] dataUsingEncoding:NSUTF8StringEncoding]];
  13. [postBody appendData:[[NSString stringWithFormat:@"</Request>"] dataUsingEncoding:NSUTF8StringEncoding]];
  14. [request setHTTPBody:postBody];
上面的代码创建了请求,可以使用同步或异步的方式发送请求

同步方式:

  1. NSHTTPURLResponse* urlResponse = nil;
  2. NSError *error = [[NSError alloc] init];
  3. NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
异步方式:
  1. NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值