[英]Call web service from console application c#
我想调用Salesforce Web服务,但出现此错误:System.dll和其他信息中发生了类型为'System.Net.WebException'的未处理的异常:其他错误:(500)内部错误。
但是当我用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;
}
}
}
最后,我可以连接到我添加以下行的Web服务:
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
此行用于使用协议TLS 1.2
您最好使用WSDL并创建服务引用,而不是手动建立请求。
更多详细信息: https : //msdn.microsoft.com/zh-cn/library/cc636424(v=ax.50).aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.