将XML发送到Web服务c#

时间:2015-09-04 11:06:26

标签: asp.net .net web-services

如何从C#(.NET)向Web服务发送XML? 不使用“添加引用” 我希望从服务中得到回应 这段代码没有例外,但我认为app无法在Web服务中自动化 我这样做了

class Program
{
    static void Main(string[] args)
    {
        string xml = "<message>"+
        "<service id="+"single"+" source = "+"AlphaName"+"/>"+
        "<to>number</to>"+
        "<body content-type="+"text/plain"+">"+
        "This is a sample message"+
        "</body>"+
        "</message>";
        Program prog = new Program();
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.life.com.ua/ip2sms/");
        request.Credentials = new NetworkCredential("login", "password");
        byte[] authBytes = Encoding.UTF8.GetBytes("login:password".ToCharArray());
        request.Headers["Authorization"] = Convert.ToBase64String(authBytes);
        prog.requests(xml);

}

}

XML请求

String requests(string xml)
    {
        WebResponse result = null;
        WebRequest req = null;
        Stream newStream = null;
        Stream ReceiveStream = null;
        StreamReader sr = null;
        string strOut = "";
        try
        {
            req = WebRequest.Create("https://api.life.com.ua/ip2sms/");
            req.Method = "POST";
            req.Timeout = 120000;
            //req.ContentType = "text/xml; charset = \"utf8\"";
            req.ContentType = "application/x-www-form-urlencoded";
            byte[] SomeBytes = null;
            SomeBytes = UTF8Encoding.UTF8.GetBytes(xml);
            req.ContentLength = SomeBytes.Length;
            newStream = req.GetRequestStream();
            newStream.Write(SomeBytes, 0, SomeBytes.Length);
            newStream.Close();
            // считываем результат работы
            result = req.GetResponse();
            ReceiveStream = result.GetResponseStream();
            Encoding encode = Encoding.UTF8;
            sr = new StreamReader(ReceiveStream, encode);
            Char[] read = new Char[256];
            int count = sr.Read(read, 0, 256);
            while (count > 0)
            {
                String str = new String(read, 0, count);
                strOut += str;
                count = sr.Read(read, 0, 256);
            }

        }
        catch (Exception ex)
        {
        }

        return strOut;
    }

但没有任何反应。谢谢!

0 个答案:

没有答案