- 我自己也是扒了好久也找到的方法,我现在简单的把代码贴出来。
- 我也在学习中有错误的请指出,共同学习。
OC 方法
+ (void) SOAPBody:(NSString *)soapBody success:(void (^)(id responseObject))success failure:(void(^)(NSError *error))failure {
NSString *sopStr = [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:Body>\
<methodName xmlns=\"命名空间">\
<param>%@</param>\
</methodName>\
</soap:Body>\
</soap:Envelope>",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 += "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
message += "<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/\">"
message += "<soap:Body>"
message += "<\(methodName) xmlns=\"命名空间">"
message += "<\(params)>\(paramValues)</\(params)>"
message += "</\(methodName)>"
message += "</soap:Body>"
message += "</soap:Envelope>"
print("请求消息体: \(message)")
return message
}
网友评论