无法将XML字符串和SOAP信封发布到Web服务

时间:2014-01-15 01:08:54

标签: xml web-services asmx

我得到了这个:错误:在写入所有字节之前无法关闭流!

我不确定如何传递SOAP信封和XML字符串内容以将其POST到Web服务器。我使用WEB API,但我也需要使用Web服务。 我查看了一些样本并提出了这段代码:

string methodName = "HelloWorld2";
byte[] xmlContent = Encoding.UTF8.GetBytes(xml);

StringBuilder soapRequest = new StringBuilder("<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"");
soapRequest.Append(" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" ");
soapRequest.Append("xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body>");
soapRequest.Append("<HelloWorld2Response xmlns=\"http://tempuri.org/\"><HelloWorld2Result>string</HelloWorld2Result></HelloWorld2Response>");
soapRequest.Append("</soap:Body></soap:Envelope>");

WebRequest webRequest = WebRequest.Create("http://server01/API2/ServerInfoImport.asmx");
HttpWebRequest httpRequest = (HttpWebRequest)webRequest;
httpRequest.Method = "POST";
httpRequest.ContentType = "text/xml; charset=utf-8";
httpRequest.Headers.Add("SOAPAction: http://tempuri.org/" + methodName);
httpRequest.ProtocolVersion = HttpVersion.Version11;
httpRequest.Credentials = CredentialCache.DefaultCredentials;
httpRequest.ContentLength = xmlContent.Length + soapRequest.Length;

Stream requestStream = httpRequest.GetRequestStream();
//Create Stream and Complete Request             
StreamWriter streamWriter = new StreamWriter(requestStream, Encoding.ASCII);

streamWriter.Write(soapRequest.ToString());
streamWriter.Write(xmlContent);
streamWriter.Close();           //<=== ERROR: Cannot close stream until all bytes are written!

//Get the Response    
HttpWebResponse wr = (HttpWebResponse)httpRequest.GetResponse();
StreamReader srd = new StreamReader(wr.GetResponseStream());
string resulXmlFromWebService = srd.ReadToEnd();

以下是Web服务:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class ServerInfoImport : System.Web.Services.WebService
{
    [WebMethod(Description = "The Hello World default method")]
    public string HelloWorld()
    {
        return "Hello World";
    }

    [WebMethod]
    public string HelloWorld2(string xml)
    {
        string partialContent = xml.Substring(1, 20);
        return partialContent;
    }
}

有什么想法吗?这真让我抓狂! 谢谢!

0 个答案:

没有答案