您的位置:首页 > 理论基础 > 计算机网络

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];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据 xml 网络