如何使用webRequest Class

时间:2015-07-22 10:24:02

标签: c# curl webrequest

我的c#programm问题是向在线电话系统发送或接收cURL请求,我希望在那里得到一些帮助:)

我将这样的命令发送到服务器:

curl https://api.placetel.de/api/test \
    -d 'api_key=XXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXXXXXXXXXXXXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXX'

服务器发回XML:

<?xml version="1.0" encoding="UTF-8"?>
<hash>
  <result>1</result>
  <result-code>success</result-code>
  <descr>test login successful v1.1</descr>
</hash>

我试过WebRequest Class(msdn)

来自电话在线系统提供商的API documentation,但仅限德语。

好的,连接适用于此:

        WebRequest request = WebRequest.Create("https://api.placetel.de/api/test.xml");
        request.Method = "POST";
        string postData = "-d 'api_key=XXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXXXXXXXXXXXXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXX'";
        byte[] byteArray = Encoding.UTF8.GetBytes(postData);

向我展示服务器的“答案”我试试这个:

            Stream dataStream = request.GetRequestStream();              
            dataStream.Write(byteArray, 0, byteArray.Length);                
            dataStream.Close();               
            WebResponse response = request.GetResponse();
           Console.WriteLine(((HttpWebResponse)response).StatusDescription);
            dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            string responseFromServer = reader.ReadToEnd();
            Console.WriteLine(responseFromServer);
            reader.Close();
            dataStream.Close();
            response.Close();

现在我收到错误消息:

Stream dataStream = request.GetRequestStream();
“System.dll中的System.Net.WebException错误”与服务器的连接失败

如何解决此问题并显示服务器的“答案”。

1 个答案:

答案 0 :(得分:0)

WebRequest request = WebRequest.Create("https://api.placetel.de/api/test.xml");
            request.Method = "POST";
            string postData = "api_key=XXXXXXXXXXXXXXX";
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);


            Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();
            WebResponse response = request.GetResponse();
            textBox1.Text = (((HttpWebResponse)response).StatusDescription);      
            //Console.WriteLine(((HttpWebResponse)response).StatusDescription);
            dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            string responseFromServer = reader.ReadToEnd();
            textBox2.Text = (responseFromServer);
            reader.Close();
            dataStream.Close();
            response.Close();

作品:)谢谢