OC 、Swift 3.0 调用 webservice 接口

  • 我自己也是扒了好久也找到的方法,我现在简单的把代码贴出来。
  • 我也在学习中有错误的请指出,共同学习。
OC 方法
+ (void) SOAPBody:(NSString *)soapBody success:(void (^)(id responseObject))success failure:(void(^)(NSError *error))failure {

    NSString *sopStr = [NSString stringWithFormat:@"\
                        \
                        \
                        \
                        %@\
                        \
                        \
                        ",soapBody];
   NSURL *URL = [NSURL URLWithString:@"地址"];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:[sopStr dataUsingEncoding:NSUTF8StringEncoding]];
    [request addValue:@"text/xml; charset=utf-8"forHTTPHeaderField:@"Content- Type"];
    [request addValue:[NSString stringWithFormat:@"%zd", sopStr.length] forHTTPHeaderField:@"Content-Length"];

    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];
        success(result);
        if(error) {
        failure(error);
        }
    }];
    [task resume];
}
//获取的数据类型是XML,需要进行XML解析
Swift方法
func reqWebService() {
        let URL = NSURL(string: "地址")!

        let mutableURLRequest: NSMutableURLRequest = NSMutableURLRequest(url:URL as URL)
        
        let values = "{\"Cmd\": \"W0010\", \"RegCode\": \"admin\",\"KeyCode\": \"admin\",\"Data\": \"\"}";
        let soapMsg: String = toSoapMessage(methodName: "gasWatch", params: "param", paramValues: values)

        mutableURLRequest.setValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")

        mutableURLRequest.setValue(String(soapMsg), forHTTPHeaderField: "Content-Length")
        mutableURLRequest.httpMethod = "POST"
        mutableURLRequest.httpBody = soapMsg.data(using: String.Encoding.utf8)

        let task:URLSessionDataTask = URLSession.shared.dataTask(with: mutableURLRequest as URLRequest) { (data, response, error) in
            let result = NSString.init(data: data!, encoding: String.Encoding.utf8.rawValue) 
            print(result)
        }
        task.resume()  
    }
    
    func toSoapMessage(methodName: String, params: String, paramValues: String) -> String {
        var message: String = String()
        message += ""
        message += ""
        message += ""
        message += "<\(methodName) xmlns=\"命名空间">"
        message += "<\(params)>\(paramValues)"
        message += ""
        message += ""
        message += ""
        print("请求消息体: \(message)")
        return message
    }

你可能感兴趣的:(OC 、Swift 3.0 调用 webservice 接口)