Soap访问Webservice

2017-02-20  本文已影响16人  张三儿

1>这东西挺恶心的大体上是拼接请求头,根据xml的要求拼接所有参数

POST /App.asmx HTTP/1.1
Host: 192.168.70.100
Content-Type: text/xml; charset=utf-8
Content-Length: lengthSOAPAction: "http://www.cnpc.com.cn/GetLocation"

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Header>
    <RequestHeader xmlns="http://www.cnpc.com.cn/">
      <AuthUsername>string</AuthUsername>
      <AuthPassword>string</AuthPassword>
    </RequestHeader>
  </soap:Header>
  <soap:Body>
    <GetLocation xmlns="http://www.cnpc.com.cn/">
      <studentUid>string</studentUid>
    </GetLocation>
  </soap:Body>
</soap:Envelope>

代码实现

NSString *soapMessage = [NSString stringWithFormat:@"<?xml version=\"1.0\" encoding=\"utf-8\"?>\
                             <soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\
                             xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\
                             <soap:Header>\
                             <RequestHeader xmlns=\"http://www.cnpc.com.cn/\">\
                             <AuthUsername>string</AuthUsername>\
                             <AuthPassword>string</AuthPassword>\
                             </RequestHeader>\
                             </soap:Header>\
                             <soap:Body>\
                             <GetLocation xmlns=\"http://www.cnpc.com.cn/\">\
                             <studentUid>%@</studentUid>\
                             </GetLocation>\
                             </soap:Body>\
                             </soap:Envelope>",studentUid];
    
    NSURL *Url = [NSURL URLWithString:@"http://192.168.70.100:8999/App.asmx"];
    NSMutableURLRequest *finalRequest = [NSMutableURLRequest requestWithURL:Url];
    
    NSData *soapdata = [soapMessage dataUsingEncoding:NSUTF8StringEncoding];
    NSString *messageLength=[NSString stringWithFormat:@"%ld",[soapMessage length]];
    
    [finalRequest addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [finalRequest addValue:@"http://www.cnpc.com.cn/GetLocation" forHTTPHeaderField:@"SOAPAction"];
    [finalRequest addValue:@"192.168.70.100" forHTTPHeaderField:@"HOST"];
    [finalRequest addValue:messageLength forHTTPHeaderField:@"Content-Length"];
    [finalRequest setHTTPMethod:@"POST"];
    [finalRequest setHTTPBody:soapdata];
    
    
    [[[NSURLSession sharedSession] dataTaskWithRequest:finalRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        if (error) {
            NSLog(@"连接错误 %@",error);
            return;
        }

上一篇下一篇

猜你喜欢

热点阅读