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

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

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

1、NSMutableURLRequest发送普通数据

view plain copy to clipboard print ?
  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];

服务器端代码:

view plain copy to clipboard print ?
  1. <%
  2. String name = request.getParameter(“name”);
  3. System.out.println(“name=”+name);
  4. %>

2、NSMutableURLRequest发送xml

view plain copy to clipboard print ?
  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];

上面的代码创建了请求,可以使用同步或异步的方式发送请求

同步方式:

view plain copy to clipboard print ?
  1. NSHTTPURLResponse* urlResponse = nil;
  2. NSError *error = [[NSError alloc] init];
  3. NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];

异步方式:

view plain copy to clipboard print ?
  1. NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];