1. 程式人生 > >C#使用Http的Post方式請求webservice

C#使用Http的Post方式請求webservice

java服務 aps 跨語言 數據 name 發現 url java 差異

webservice是以前比較流行的跨系統、跨語言、跨平臺的數據交互技術。最近工作中調用Java作為服務端開放的webser,
我是通過VS205生成webservice工具類的方式進行接口調用的。用這種方式的理由是對自身的工程項目影響較小,系統
生成一個工具了,只需要將此工具類放置對應的目錄下並包含在項目中即可。
這種方式看似很好,但是我最近的這個項目出現一個奇怪的問題,就是用webservice工具類調用接口返回值居然是null,
用SoapUI測試卻是正常返回了數據,於是我使用Postman測試了下,發現Postman也返回了數據,不過返回的xml數據需要
html轉義下。 網上搜索了下,大概意思是指java服務端在將java對象進行序列化過程中可能有指定的數據類型與C#序列化存在差異。
反正意思大概是這個意思,我在想竟然Postman可以交互,那我直接用http請求得了。

用http請求,直接將soapUI中的入參在代碼中拼接好即可,如下:

技術分享
 1  /// <summary>
 2         /// 生成Http Post入參
 3         /// </summary>
 4         /// <param name="post"></param>
 5         /// <returns></returns>
 6         private string CreateHttpRequest(string post)
 7         {
 8             StringBuilder sb = new
StringBuilder(); 9 sb.Append(@"<soapenv:Envelope xmlns:soapenv=‘http://schemas.xmlsoap.org/soap/envelope/‘ xmlns:exc=訪問地址‘>"); 10 sb.Append("<soapenv:Header/>"); 11 sb.Append("<soapenv:Body>"); 12 sb.Append("<exc:HisWxEccute>"); 13 sb.Append("
<exc:xmlString>"); 14 sb.Append(post); 15 sb.Append("</exc:xmlString>"); 16 sb.Append("</exc:HisWxEccute>"); 17 sb.Append("</soapenv:Body>"); 18 sb.Append("</soapenv:Envelope>"); 19 return sb.ToString(); 20 }
View Code

使用方法:

1  string input = CreateHttpRequest(req);              
2  string result = WebRequestHelper.Current.HttpPost(Url, input, Encoding.UTF8, Encoding.UTF8);

感覺這種方式比生產webservice代理類更爽啊啊~

C#使用Http的Post方式請求webservice