我是C#的新手。我想使用 C# 从桌面应用程序发送消息,为此我从移动公司 (Telenor) 购买了一个 API。根据他们的文档,首先我必须通过向此 URL (https://telenorcsms.com.pk:27677/corporate_sms2/api/auth.jsp?msisdn=xxxx&password=xxx) 发送请求来获取身份验证 ID,它以 XML 格式为我提供响应,如下所示:
<?xml version="1.0" encoding="UTF-8" ?>
<corpsms>
<command>Auth_request</command>
<data>Session ID</data>
<response>OK</response>
</corpsms>
现在我需要节点<data>
会话 ID,以进一步用于发送消息,例如 (https://telenorcsms.com.pk:27677/corporate_sms2/api/sendsms.jsp?session_id=xxxx&to=923xxxxxxxxx,923xxxxxxxxx,923xxxxxxxxx&text=xxxx&mask=xxxx)。
我尝试了许多方法来显示会话ID并使用它,但不知道该怎么做。这是我的代码:
WebClient client = new WebClient ();
client.Headers.Add ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
Stream data = client.OpenRead ("https://telenorcsms.com.pk:27677/corporate_sms2/api/auth.jsp?msisdn=xxxx&password=xxx");
StreamReader reader = new StreamReader (data);
StreamReader objreadr = new StreamReader(data);
string s = reader.ReadToEnd();
您可以使用 Linq to Xml
var sessionid = XDocument.Parse(s).Descendants("data").First().Value;
首先将文件保存到某个路径,然后使用此代码在 xml 中获取所需的节点。
public void Load()
{
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
XmlDocument xmldoc = new XmlDocument();
XmlNodeList xmlnode;
xmldoc.Load(fs);
xmlnode = xmldoc.GetElementsByTagName("corpsms");
for (int i = 0; i < xmlnode.Count; i++)
{
string str = string.Format("ID: {0}rnName:{0}", xmlnode[i].ChildNodes.Item(0).InnerText, xmlnode[i].ChildNodes.Item(1).InnerText);//Your Data will exist at node 1
MessageBox.Show(str);
}
}
var url = @"https://example.com/api/auth.jsp";
var nvc = new NameValueCollection();
nvc.Add("msisdn", "xxxxxxxxxxxx");
nvc.Add("password", "xxxx");
var client = new System.Net.WebClient();
var data = client.UploadValues(url, nvc);
var res = System.Text.Encoding.ASCII.GetString(data);
string GetResponse = res.ToString();
string sessionid = XDocument.Parse(res).Descendants("data").First().Value;
url = @"https://telenorcsms.com.pk:27677/corporate_sms2/api/sendsms.jsp";
nvc = new NameValueCollection();
nvc.Add("msisdn", "xxxxxxxxx");
nvc.Add("session_id",sessionid);
nvc.Add("to", textBox1.Text);
nvc.Add("text",textBox2.Text);
data = client.UploadValues(url, nvc);
res = System.Text.Encoding.ASCII.GetString(data);