XML数据包网络请求
2016-03-20 19:26
453 查看
刚来的这家公司项目后台数据是XML,数据请求是是发送XML数据包到后台,在网上找了半天都没有满意的,自己用原生的和AFNetworking试了一下。
原生的代码如下:
NSString *urlString = [NSString stringWithFormat:@"http://xxxxxx"]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setURL:[NSURL URLWithString:urlString]]; [request setHTTPMethod:@"POST"]; NSString *contentType = [NSString stringWithFormat:@"text/xml"]; [request addValue:contentType forHTTPHeaderField: @"Content-Type"]; NSMutableString * postString = [NSMutableString stringWithFormat:@"<?xml version=\"1.0\" encoding=\"utf-8\"?>"]; [postString appendString:@"<Login>"]; [postString appendFormat:@"<UserName>%@</UserName>", self.accountTF.text]; [postString appendFormat:@"<Pwd>%@</Pwd>", self.passwordTF.text]; [postString appendString:@"</Login>"]; NSString * postBodyString = [postString copy]; NSData * postBody = [postBodyString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]; [request setHTTPBody:postBody]; NSHTTPURLResponse* urlResponse = nil; NSError *error = [[NSError alloc] init]; NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error]; NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; NSLog(@"Response Code: %ld", [urlResponse statusCode]); if ([urlResponse statusCode] >= 200 && [urlResponse statusCode] < 300) { NSLog(@"Response: %@", result); }
AFNetworking的代码如下:
NSString *urlString = [NSString stringWithFormat:@"http://xxxxxx"]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setURL:[NSURL URLWithString:urlString]]; [request setHTTPMethod:@"POST"]; NSString *contentType = [NSString stringWithFormat:@"text/xml"]; [request addValue:contentType forHTTPHeaderField: @"Content-Type"]; NSMutableString * postString = [NSMutableString stringWithFormat:@"<?xml version=\"1.0\" encoding=\"utf-8\"?>"]; [postString appendString:@"<Login>"]; [postString appendFormat:@" [postString appendFormat:@"<UserName>%@</UserName>", self.accountTF.text]; [postString appendFormat:@"<Pwd>%@</Pwd>", self.passwordTF.text]; [postString appendString:@"</Login>"]; NSString * postBodyString = [postString copy]; NSData * postBody = [postBodyString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]; [request setHTTPBody:postBody]; AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; operation.responseSerializer = [AFXMLParserResponseSerializer serializer]; operation.responseSerializer.acceptableContentTypes = [operation.responseSerializer.acceptableContentTypes setByAddingObject:@"text/xml"]; [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { } failure:^(AFHTTPRequestOperation *operation, NSError *error) { }]; [operation start];