使用Web请求调用WCF服务
最近配合公司搞java的同事做web项目,要求调用之前部署的WCF服务。同事找了一些java调WCF的三方包(如 axis2),都不太好使,有的直接就是报错(估计原因是把所有的数据成员都弄到一个类里解析,成员的属性有名称相同的就报错)。还好当时使用的是basichttpbinding,可以直接通过拼字符串调用(别的binding没试,有空再说吧)。
先确定WCF地址
string baseAddress = "http://127.0.0.1/WCFTest/Service/WCTestService.svc";
服务提供一个Execute(Request r)的方法,返回值为Response。Request和Response都为基类。
然后就是万恶的拼soap字符串了
string soapBody = @"<s:Envelope xmlns:s=""http://schemas.xmlsoap.org/soap/envelope/""> <s:Body> <Execute xmlns=""http://WCF契约命名空间""> <request i:type=""Request实体类的名称"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance""> <Request属性1>属性1的值</Request属性1> <Request属性2>属性2的值</Request属性2> </request> </Execute> </s:Body> </s:Envelope>";
然后就是把字符串以web请求传到服务器上
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(baseAddress); req.Method = "post"; req.Headers["SOAPAction"] = "http://tempuri.org/契约接口名称/调用方法"; req.ContentType = “text/xml”; byte[] bodyBytes = Encoding.UTF8.GetBytes(soapBody); req.GetRequestStream().Write(bodyBytes, 0, bodyBytes.Length); req.GetRequestStream().Close(); HttpWebResponse resp; try { resp = (HttpWebResponse)req.GetResponse(); } catch (WebException e) { resp = (HttpWebResponse)e.Response; } if (resp == null) { responseBody = null; Console.WriteLine("Response is null"); } else { Stream respStream = resp.GetResponseStream(); if (respStream != null) { //都有stream了还不好说 嘎嘎 } else { Console.WriteLine("HttpWebResponse.GetResponseStream returned null"); } }
posted on 2013-05-06 18:45 beastplus 阅读(2342) 评论(0) 编辑 收藏 举报