.net 调用java或者Java调用.net返回的数据转换问题

Posted on 2015-07-16 23:06  laojiahuo  阅读(246)  评论(0编辑  收藏  举报

经常发现这类问题,主要是返回的数据转换问题造成,一般情况下不要直接引用wsdl的方式(如果的调用.Net开发的webservice可以),用HttpWebRequest方式获取返回的数据,然后再解析,这种方式比引用wsdl成功率高,至于如何传参数,可以用
SoapUI工具进行分析,能看到该怎样传参数
还有用HTTPAnalyzerFull工具可以进行抓包,看看提交和返回的是什么内容

不管是.net 调用java或者Java调用.net,一般用以上两个工具都能解决问题

public string GetGsReturn(string url, StringBuilder param)//提交到webservice并返回结果
  {
   string responseString = string.Empty;
   try
   {
    byte[] bs = Encoding.UTF8.GetBytes(param.ToString());

    HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
    myRequest.Method = "post";

    myRequest.Headers.Add("SOAPAction", "\"\"");
    myRequest.Headers.Add("Accept-Encoding", "gzip,deflate");
    myRequest.ContentType = "text/xml; charset=utf-8";

    myRequest.KeepAlive = true;
    myRequest.ContentLength = bs.Length;
    myRequest.UserAgent = "Apache-HttpClient/4.1.1 (java 1.5)";

    Stream reqStream = myRequest.GetRequestStream();
    reqStream.Write(bs, 0, bs.Length);

    HttpWebResponse myResponse;
    try
    { myResponse = (HttpWebResponse)myRequest.GetResponse(); }
    catch (WebException ex)
    { myResponse = (HttpWebResponse)ex.Response; }
    if (myRequest != null)
    {
     StreamReader sr = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
     responseString = sr.ReadToEnd();//返回的数据
    }
   }
   catch (Exception ex)
   {
    responseString = ex.Message;
   }
   return responseString;
  }

一个参数用例,具体看你的实际需求

 

    StringBuilder param = new StringBuilder();
    param.AppendLine("<?xml version='1.0' encoding='utf-8'?>");
    param.AppendLine("<soapenv:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:web='http://webservice.protal.ems.com'>");
    param.AppendLine("<soapenv:Header/>");
    param.AppendLine("<soapenv:Body>");

    param.AppendLine("<web:sendSMS soapenv:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'>");
    param.AppendLine("<enterpriseID xsi:type='xsd:string'>15644</enterpriseID>");
    param.AppendLine("<loginName xsi:type='xsd:string'>admin</loginName>");
    param.AppendLine("<password xsi:type='xsd:string'>511c6269b5eb69538c71ab372529fb1d</password>"); //741123
    param.AppendLine("<smsId xsi:type='xsd:string'></smsId>");
    param.AppendLine("<subPort xsi:type='xsd:string'></subPort>");
    param.AppendLine("<content xsi:type='xsd:string'>" + smstxt + "</content>");
    param.AppendLine("<mobiles xsi:type='xsd:string'>" + tels + "</mobiles>");
    param.AppendLine("<sendTime xsi:type='xsd:string'></sendTime>");
    param.AppendLine("</web:sendSMS>");

    param.AppendLine("</soapenv:Body>");
    param.AppendLine("</soapenv:Envelope>");

    string rtnstr = GetGsReturn(SmsUrl, param);//传送参数并返回结果

 

Copyright © 2024 laojiahuo
Powered by .NET 8.0 on Kubernetes