从控制台应用程序调用Web服务c#

时间:2017-02-09 18:27:37

标签: c# web-services console-application

我想调用salesforce Web服务,但是我收到此错误:类型为#System; Net.WebException'的未处理异常。发生在System.dll和附加信息:错误en servidor remoto:(500)错误interno del servidor。

但是当我用Java调用相同的Web服务时,我不会收到任何错误。

这是我正在使用的C#代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {

        static String ST = "some_string";
        static String pwd = "password";
        static String userName = "myusername";
        static String SERVER_URL;
        static String SESSION_ID;

        static void Main(string[] args)
        {
            string url = " https://test.salesforce.com/services/Soap/u/30.0";
            string details = CallRestMethod(url);
        }

        public static string CallRestMethod(string url)
        {
            HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
            webrequest.Method = "POST";
            webrequest.ContentType = "text/xml;charset=UTF-8";
            webrequest.Headers.Add("SOAPAction", "\"\"");

            String input = "<Envelope xmlns=\"http://schemas.xmlsoap.org/soap/envelope/\"><Header/><Body><login xmlns=\"urn:partner.soap.sforce.com\"><username>" + userName + "</username><password>" + pwd + ST + "</password></login></Body></Envelope>";
            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] byte1 = encoding.GetBytes(input);

            webrequest.GetRequestStream().Write(byte1, 0, byte1.Length);

            /*Stream newStream = webrequest.GetRequestStream();
            newStream.Write(byte1, 0, byte1.Length);
            newStream.Close();*/

            Console.WriteLine(webrequest.Headers);

            HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();
            Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
            StreamReader responseStream = new StreamReader(webresponse.GetResponseStream(), enc);
            string result = string.Empty;
            result = responseStream.ReadToEnd();
            webresponse.Close();
            return result;
        }
    }
}

2 个答案:

答案 0 :(得分:2)

最后,我可以连接到我添加此行的Web服务:

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

此行用于使用协议TLS 1.2

答案 1 :(得分:0)

最好使用WSDL并创建服务引用,而不是手工构建请求。

更多详情:https://msdn.microsoft.com/en-us/library/cc636424(v=ax.50).aspx