前言
很長時間沒有寫點東西,兩個月左右了吧。一直在看其他的東西,今天說一下WebService的請求怎么寫。
首先,這里你只會看到怎么用(使用的系統(tǒng)的NSURLSession),不會看到有關于WebService的理論知識點。知識點網上有很多,這里只說怎么使用(打死我都不會告訴你,其實是我也不會相關的知識點)。
沒有相關dmeo看,字寫再多都扯淡。
正文
代碼片段
首先我先把代碼貼出來
OC:
- (void)webServiceConnectionNameSpace:(NSString *)nameSpace withUrlStr:(NSString *)urlStr withMethod:(NSString *)method{
// 創(chuàng)建SOAP消息,內容格式就是網站上提示的請求報文的實體主體部分
NSString *soapMsg = [NSString stringWithFormat:
@"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
"<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/\">\n"
"<soap:Body>\n"
"<%@ xmlns=\"%@\">\n"
"<byProvinceName>%@</byProvinceName>\n"
"</%@>\n"
"</soap:Body>\n"
"</soap:Envelope>\n",method,nameSpace,@"北京",method];
NSLog(@"%@", soapMsg);
// 創(chuàng)建URL
NSURL *url = [NSURL URLWithString: urlStr];
//計算出soap所有的長度,配置頭使用
NSString *msgLength = [NSString stringWithFormat:@"%lu", (unsigned long)[soapMsg length]];
//創(chuàng)建request請求,把請求需要的參數配置
NSMutableURLRequest *request=[[NSMutableURLRequest alloc]init];
// 添加請求的詳細信息,與請求報文前半部分的各字段對應
//請求的參數配置,不用修改
[request setTimeoutInterval: 10 ];
[request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
[request setURL: url ] ;
[request setHTTPMethod:@"POST"];
[request setValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
//soapAction的配置
[request setValue:[NSString stringWithFormat:@"%@%@",nameSpace,method] forHTTPHeaderField:@"SOAPAction"];
[request setValue:msgLength forHTTPHeaderField:@"Content-Length"];
// 將SOAP消息加到請求中
[request setHTTPBody: [soapMsg dataUsingEncoding:NSUTF8StringEncoding]];
// 創(chuàng)建連接
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error) {
NSLog(@"失敗%@", error.localizedDescription);
}else{
NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"結果:%@\n請求地址:%@", result, response.URL);
//系統(tǒng)自帶的
NSXMLParser *par = [[NSXMLParser alloc] initWithData:[result dataUsingEncoding:NSUTF8StringEncoding]];
[par setDelegate:self];//設置NSXMLParser對象的解析方法代理
[par parse];//調用代理解析NSXMLParser對象,看解析是否成功
}
}];
[task resume];
}
//獲取節(jié)點間內容
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
NSLog(@"%@", string);
}
Swift:
/*
nameSpace:命名空間
urlStr:請求接口
method:方法體
*/
func webServiceConnect( nameSpace:String, urlStr:String, method:String){
//soap的配置
let soapMsg:String = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"+"<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/\">\n"+"<soap:Body>\n"+"<"+method+" xmlns=\""+nameSpace+"\">\n"+"<byProvinceName>"+"北京"+"</byProvinceName>\n"+"</"+method+">\n"+"</soap:Body>\n"+"</soap:Envelope>\n"
let soapMsg2:NSString = soapMsg as NSString
//接口的轉換為url
let url:URL = URL.init(string:urlStr)!
//計算出soap所有的長度,配置頭使用
let msgLength:NSString = NSString.init(format: "%i", soapMsg2.length)
//創(chuàng)建request請求,把請求需要的參數配置
var request:URLRequest = NSMutableURLRequest.init() as URLRequest
//請求的參數配置,不用修改
request.timeoutInterval = 10
request.cachePolicy = .reloadIgnoringLocalCacheData
request.url = url
request.httpMethod = "POST"
//請求頭的配置
request.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.addValue(msgLength as String, forHTTPHeaderField: "Content-Length")
request.httpBody = soapMsg.data(using: String.Encoding.utf8)
//soapAction的配置
let soapActionStr:String = nameSpace + method
request.addValue(soapActionStr, forHTTPHeaderField: "SOAPAction")
//開始網絡session請求的單例創(chuàng)建
let session:URLSession = URLSession.shared
//開始請求
let task:URLSessionDataTask = session.dataTask(with: request as URLRequest , completionHandler: {( data, respond, error) -> Void in
if (error != nil){
print("error is coming")
}else{
//結果輸出
let result:NSString = NSString.init(data: data!, encoding: String.Encoding.utf8.rawValue)!
print("result=\(result),\n adress=\(request.url)")
}
})
//提交請求
task.resume()
}
講解
(個人的理解)
WebService的請求比普通的接口請求復雜的地方就是soap和soapAction的配置。
soap
<?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>
<getSupportCity xmlns="http://WebXml.com.cn/">
<byProvinceName>北京</byProvinceName>
</getSupportCity>
</soap:Body>
</soap:Envelope>
一句一句解讀一下
<?xml version="1.0" encoding="utf-8"?>
這個沒啥說的吧,就xml的版本和編碼。
<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的固定部分,直接用就行了。我這個是1.0版本的,有2.0版本的。至于用哪個看你們的服務器端了。
<soap:Body>
<getSupportCity xmlns="http://WebXml.com.cn/">
<byProvinceName>北京</byProvinceName>
</getSupportCity>
</soap:Body>
body包裹著這次請求所需要的參數,和普通的接口參數不同的是WebService的參數都是放在xml里面。
<getSupportCity xmlns="http://WebXml.com.cn/">
這句很關鍵的,首先,知道這次請求的方法體是什么,然后請求的命名空間是什么。這兩個參數都是需要后臺給你的,不是隨意寫的。認真想想也是哈,你給人家參數,人家后臺要知道這個參數對應的是哪一個方法里面的哪一個參數吧。就好比說你去一所學校找個叫張三的人,學校叫張三的可能很多,你要知道是哪個班的張三才行吧,一個道理都是。
<byProvinceName>北京</byProvinceName>
這個是你上傳的參數字段,參數的名字是后臺給你的。一定要對應,有的后臺可能比較懶,一個參數名對應幾個參數,這都需要注意。
soapAction
這個我個人理解就是你的命名空間和方法體的字符串拼寫。
[request setValue:[NSString stringWithFormat:@"%@%@",nameSpace,method] forHTTPHeaderField:@"SOAPAction"];
這個一定不能缺少,不然請求會成功,但是會顯示錯誤:
其他的就沒啥說的了,NSURLSession請求就行了。
然后可以通過NSXMLParser去解析xml,代理去拿到返回的請求數據內容(直接得到的data轉換為字符串會發(fā)現得到的是含有soap的內容)。
最后請求成功:
結語
這次WebService只是我需要用一下它然后去做的,方方面面都沒有考慮只是簡單的使用了一下。所以和題目一樣,這是一個簡單的使用dmeo。有問題可以留言說,盡量解決的。