使用苹果自带的类NSMutableURLRequest post发送数据
使用苹果自带的类NSJSONSerialization解析数据
省去使用第三方库带来的烦恼
//传送json数据
- (IBAction)sendJsonData:(id)sender
{
// NSURL *url = [[NSURL alloc] initWithString:@"http://tianjianweisai.xicp.net:9090/CloserWebService/servlet/LoginServlet"];
NSURL *url = [[NSURL alloc] initWithString:@"http://192.168.0.210:8080/CloserWebService/servlet/LoginServlet"];
//创建一个请求,用于发送
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
assert(request != nil);
[request setTimeoutInterval:5.0f];
NSString *name = @"smile";
NSString *age = @"17";
//使用苹果自带的类NSJSONSerialization生成json
NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:name,@"username",age,@"password",nil];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
//下面的二次转换很重要,因为使用NSJSONSerialization生成的data不能直接传给服务端,服务端必须要根据一个名字来读取数据,下面就是给jsonData格式化并取个名称
NSString *strData = [[NSString alloc] initWithData:jsonData encoding:NSASCIIStringEncoding];
NSLog(@"strData:%@",strData);
NSString *postData = [[NSString alloc] initWithFormat:@"message%@",strData];
NSData *sendData = [postData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; //这个sendData才可以发送给服务端
NSString *postLength = [NSString stringWithFormat:@"%d", [sendData length]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:sendData];
//使用NSURLConnection的类方法sendSynchronousRequest:request发送数据
[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[NSError alloc] init];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
}