之前有篇博文介绍从服务器下载数据,再写一篇基于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];
异步方式的返回数据由代理负责处理。