使用ios调用web Service成功案例

实现两个int类型相加返回和,在使用的时候导入需要用到的类库,具体使用详见:

这里写图片描述

http://blog.csdn.net/iosweb/article/details/49593997
代码截图:
这里写图片描述
这里写图片描述
代码如下:

- (void)viewDidLoad
{
    [super viewDidLoad];

    int i = 5;
    int j = 12;

    NSString *soapMessage =
    [NSString stringWithFormat:
     @"<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'>\n"
     "<soap12:Body>\n"
     "<add xmlns='http://tempuri.org/'>\n"
     "<a>%i</a>"
     "<b>%i</b>"
     "</add>\n"//add是方法名
     "</soap12:Body>\n"
     "</soap12:Envelope>\n",i,j
     ];
//    url端口html
    NSURL *url = [NSURL URLWithString: @"http://m.93966.net:1133/BmIndexPageWeb/wsTest.asmx"];
    req = [NSMutableURLRequest requestWithURL:url];
    NSString *msgLength = [NSString stringWithFormat:@"%lu",(unsigned long)[soapMessage length]];
    [req addValue:@"http://tempuri.org/add" forHTTPHeaderField:@"SOAPAction"];
    [req addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [req addValue:msgLength forHTTPHeaderField:@"Content-Length"];
    [req setHTTPMethod:@"POST"];
    [req setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];

    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
    if(conn)
    {
       webData = [NSMutableData data];
    }

}
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [webData setLength:0];

}
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{

    [webData appendData:data];
//    data转换成字符串类型
//    NSString* aStr= [[NSString alloc] initWithData:webData encoding:NSASCIIStringEncoding];
//    NSLog(@"%@",aStr);


}
// 当请求失败时的相关操作;
- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"%@",error);
}
//回调
- (void) connectionDidFinishLoading:(NSURLConnection *) connection
{
//    NSLog(@"Done. Received Bytes: %lu", (unsigned long)[webData length]);
    NSString *theXML = [[NSString alloc] initWithBytes:[webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
    NSLog(@"返回的结果: %@", theXML);
}

需要注意的2个参数:

NSURL *url = [NSURL URLWithString: @"http://m.93966.net:1133/BmIndexPageWeb/wsTest.asmx"];
//Web Service 的RUL地址
[req addValue:@"http://tempuri.org/add" forHTTPHeaderField:@"SOAPAction"];

//注意这里的参数,是名字空间加上接口方法名
下面还要我讲吗?:)接收服务器反馈数据的方法已经赤裸裸的写在代码的最后了,这个方法:

- (void) connectionDidFinishLoading:(NSURLConnection *) connection

看名字也知道它的作用。在里面得到反馈信息就OK了。返回的数据是XML格式的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值