iOS中发送xml给服务器

 
  
一、用URLSession请求
 
  
NSString *soapStr = [NSString stringWithFormat:@""1.0\" encoding=\"utf-8\"?>\
 "http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\
 xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\
 \
 \
 \
 "targetNameSpace地址/\">\
 test\
 test\
 \
 \
 "];
  
 NSURL *url=[NSURL URLWithString:@"你自己wsdl文档中对应的endpoint address"];
  
 NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
  
 // 访问方式
 [request setHTTPMethod:@"POST"];
  
 // 设置请求头(请求头也可以不设置,前两个设不设置都一样,应该默认的,但是SOAPAction我怎么都设置不对,不设置也可以,干脆不设置了)
 // [request addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
//  [request addValue:[NSString stringWithFormat:@"%zd", soapStr.length] forHTTPHeaderField:@"Content-Length"];
 //    [request addValue:@"nameSpace/methodName" forHTTPHeaderField:@"SOAPAction"];
  
 // body内容
 [request setHTTPBody:[soapStr dataUsingEncoding:NSUTF8StringEncoding]];
  
 NSURLSession *session = [NSURLSession sharedSession];
  
 NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
 NSString *result = [[NSString alloc] initWithData:data  encoding:NSUTF8StringEncoding];
  
 WJLog(@"进入成功回调Session-----结果:%@----请求地址:%@", result, response.URL);
  
 if (error) {
 WJLog(@"Session----失败----%@", error.localizedDescription);
 }
 }];
  
 [task resume];

二、用AFNetworking请求

一开始想用manager发请求,直接把XML当params发POST肯定是直接挂了,于是想要设置HTTPBody要不用AFHTTPRequestOperation?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
NSMutableURLRequest  *request=[ NSMutableURLRequest  requestWithURL:url];
  [request setHTTPMethod:@ "POST" ];
  [request setHTTPBody:[soapStr dataUsingEncoding: NSUTF8StringEncoding ]];
   
  AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
   
  // 设置返回数据格式
  operation.responseSerializer = [AFHTTPResponseSerializer serializer];
   
  [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation * _Nonnull operation,  id   _Nonnull responseObject) {
  NSString  *result = [[ NSString  alloc] initWithData:responseObject  encoding: NSUTF8StringEncoding ];
  WJLog(@ "AFN--成功--结果:%@----返回数据%@" , result, responseObject);
  } failure:^(AFHTTPRequestOperation * _Nonnull operation,  NSError  * _Nonnull error) {
  WJLog(@ "AFN--失败--%@" , error.localizedDescription);
  }];
   
  [operation start];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
NSMutableURLRequest  *request=[ NSMutableURLRequest  requestWithURL:url];
  [request setHTTPMethod:@ "POST" ];
  [request setHTTPBody:[soapStr dataUsingEncoding: NSUTF8StringEncoding ]];
   
  AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
   
  // 设置返回数据格式
  operation.responseSerializer = [AFHTTPResponseSerializer serializer];
   
  [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation * _Nonnull operation,  id   _Nonnull responseObject) {
  NSString  *result = [[ NSString  alloc] initWithData:responseObject  encoding: NSUTF8StringEncoding ];
  WJLog(@ "AFN--成功--结果:%@----返回数据%@" , result, responseObject);
  } failure:^(AFHTTPRequestOperation * _Nonnull operation,  NSError  * _Nonnull error) {
  WJLog(@ "AFN--失败--%@" , error.localizedDescription);
  }];
   
  [operation start];
这一看感觉和 NSURLSession 没多大差别,还是想用manager,关键问题就在于设置request的HTTBbody为XML,但是AFHTTPSessionManager已经把request封装了,默认用的params,怎么改?于是想改动或者添加AFN内部方法,但是总感觉这样不好,万一更新库了又要搞一遍。于是想能否拦截这个request,或者通过manager.requestSerializer设置HTTPBody,敲set浏览一下没有HTTPBody字眼的,用KVC也不行,那样还是相当于把XML当params传了,伤心绝望之时看到这个方法
[manager.requestSerializer setQueryStringSerializationWithBlock:^ NSString  *( NSURLRequest  *request,  NSDictionary  *parameters,  NSError  *__autoreleasing *error) {
    // 
}]
一看里面有request 有 params 高兴了,说不定在这里能拦截,于是直接写
[manager.requestSerializer setQueryStringSerializationWithBlock:^ NSString  *( NSURLRequest  *request,  NSDictionary  *parameters,  NSError  *__autoreleasing *error) {
     return  soapStr;
}],请求成功,高兴了。
 
接下来另一个问题了,简单封装一下,我收到的是二进制,所以把AFN封装成了个工具类,供大家参考,欢迎提出改进
 
/**
*  请求SOAP,返回NSData
*
*  @param url      请求地址
*  @param soapBody soap的XML中方法和参数段
*  @param success  成功block
*  @param failure  失败block
*/

+ ( void )SOAPData:( NSString  *)url soapBody:( NSString  *)soapBody success:( void  (^)( id  responseObject))success failure:( void (^)( NSError  *error))failure {
      
     NSString  *soapStr = [ NSString  stringWithFormat:
                          @"\
                          //www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\
                          xmlns:soap=\"http: //schemas.xmlsoap.org/soap/envelope/\">\
                          \
                          \
                          %@\
                          ",soapBody];
      
     AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
     manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
      
     // 设置请求超时时间
     manager.requestSerializer.timeoutInterval = 30;
      
     // 返回NSData
     manager.responseSerializer = [AFHTTPResponseSerializer serializer];
      
     // 设置请求头,也可以不设置
     [manager.requestSerializer setValue:@ "application/soap+xml; charset=utf-8"  forHTTPHeaderField:@ "Content-Type" ];
     [manager.requestSerializer setValue:[ NSString  stringWithFormat:@ "%zd" , soapStr.length] forHTTPHeaderField:@ "Content-Length" ];
  
     // 设置HTTPBody
     [manager.requestSerializer setQueryStringSerializationWithBlock:^ NSString  *( NSURLRequest  *request,  NSDictionary  *parameters,  NSError  *__autoreleasing *error) {
         return  soapStr;
     }];
      
     [manager POST:url parameters:soapStr success:^( NSURLSessionDataTask  * _Nonnull task,  id   _Nonnull responseObject) {
         // 把返回的二进制数据转为字符串
          NSString  *result = [[ NSString  alloc] initWithData:responseObject encoding: NSUTF8StringEncoding ];
          
         // 利用正则表达式取出之间的字符串
         NSRegularExpression  *regular = [[ NSRegularExpression  alloc] initWithPattern:@ "(?<=return\\>).*(?=  options: NSRegularExpressionCaseInsensitive  error: nil ];
          
         NSDictionary  *dict = [ NSDictionary  dictionary];
         for  ( NSTextCheckingResult  *checkingResult in [regular matchesInString:result options:0 range: NSMakeRange (0, result.length)]) {
              
             // 得到字典
             dict = [ NSJSONSerialization  JSONObjectWithData:[[result substringWithRange:checkingResult.range] dataUsingEncoding: NSUTF8StringEncoding ] options: NSJSONReadingMutableLeaves  error: nil ];
         }
         // 请求成功并且结果有值把结果传出去
         if  (success && dict) {
             success(dict);
         }
          
     } failure:^( NSURLSessionDataTask  * _Nullable task,  NSError  * _Nonnull error) {
         if  (failure) {
             failure(error);
         }
     }];
}

你可能感兴趣的:(网络请求)