最近在做一款学院新闻客户端。服务器提供者说只能用soap取数据,而且取完后会将xml和json结合。没办法,上网找soap的相关知识自学--无果一天后现在总算能拿到数据了。这个过程中遇到了不少问题。在这里mark下。
为了方便,这里就用网上一个服务端作为例子。
当然,为了偷懒,界面之类的就省了--
POST /WebServices/MobileCodeWS.asmx HTTP/1.1
Host: webservice.webxml.com.cn
Content-Type: application/soap+xml; charset=utf-8
Content-Length: length
<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
<soap12:Body>
<getMobileCodeInfo xmlns="http://WebXml.com.cn/">
<mobileCode>string</mobileCode>
<userID>string</userID>
</getMobileCodeInfo>
</soap12:Body>
</soap12:Envelope>
以这个xml为例,我们在解析时先封装soap请求信息,说白了把上面的内容变成oc字符串。
NSString *soapMsg = [NSString stringWithFormat:
@"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
"<soap12:Envelope "
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" "
"xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">"
"<soap12:Body>"
"<getMobileCodeInfo xmlns=\"http://WebXml.com.cn/\">"
"<mobileCode>%@</mobileCode>"
"<userID>%@</userID>"
"</getMobileCodeInfo>"
"</soap12:Body>"
"</soap12:Envelope>", @"……", @"……"];
其中
"<mobileCode>%@</mobileCode>"
"<userID>%@</userID>"
这两行表示我们要用实际值来取代占位符。回到我们的xml文件中
<mobileCode>string</mobileCode>
<userID>string</userID>
发现这两个参数是string类型的,所以传递两个string参数。
然后根据服务端创建url
NSURL *url = [NSURL URLWithString: @"/* …… */"];
//url不允许发--
可以看到这个字符串实际上就是第二行主机地址加上第一行url字段
接下来我们建立请求、发送信息、获得数据、解析数据。这里我们主要说前三个,并且用ASIHTTPRequest(其他方法大同小异,个人习惯asi)。获得数据后根据 xml或json解析即可(遇到bt的两个都要用,比如我--)。
建立请求:
ASIHTTPRequest * theRequest = [ASIHTTPRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMsg length]];
[theRequest addRequestHeader:@"Content-Type" value:@"application/soap+xml;charset=utf-8"];
[theRequest addRequestHeader:@"SOAPAction" value:@"webservice.webxml.com.cn”];
[theRequest addRequestHeader:@"Content-Length" value:msgLength];
这三行是添加请求头,对用xml开头那三行
然后设置请求方法为POST
[theRequest setRequestMethod:@"POST"];
将soap消息添加到请求中
[theRequest appendPostData:[soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
然后同步调用
[theRequest startSynchronous];
如果一切正常,现在就可以在theRequest的respondString中得到数据了。当然,如果有错误,不用急。如果能看到错误信息,根据信息直接改就行。如果你像我一样服务器是他人的,自己没法看到错误信息,那就从头慢慢找找。这里我列几个我犯的错误
1、检查一下你的url有没有写对,举个例子,我想得到的是getDatabaseInfo这个里面的内容,然后我在url末尾加上了/getDatabaseInfo 于是,半小时 --
2、确认一下同步调用,这里我一开始写的异步调用,结果返回null
3、(可以说是废话)仔细检查各个字符串是否正确,比如设置头的时候、copy soap信息的时候……
4、确保传递的参数正确(类型、值)
其他方面估计就算有也比较少见了吧。
到目前为止我们成功获得了数据。接下来就是解析了,理论上比较简单了(虽然我还是遇到了麻烦——调用sbjson的objectByString获得的数组中文显示竟然出了问题--)