System.Net.HttpWebRequest响应

时间:2017-12-01 17:24:58

标签: c# asp.net

需要一些帮助来解决问题。第一次这样做,我读过的所有内容似乎都没有帮助。我正在尝试从api调用获得响应并在我的标签中取回结果,但我得到的是我的标签中的 System.Net.HttpWebRequest ,所以它的发送和回复至少。 我还需要做些什么来恢复预期的反应吗?

    ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
    WebRequest req = WebRequest.Create(@"https://server.net/api/v1/.." + Id_TextBox.Text);
    req.Method = "POST";
    req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("Login:######"));
    HttpWebResponse resp = (HttpWebResponse)req.GetResponse();//(HttpWebResponse)req.GetResponse() as HttpWebResponse;
    myString_Label.Text = req.ToString();

谢谢!

1 个答案:

答案 0 :(得分:0)

您必须执行以下操作,您也可以从MSDN获得相同的内容

https://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.getresponsestream(v=vs.110).aspx

HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream receiveStream = resp.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
// Pipes the stream to a higher level stream reader with the required encoding format. 
StreamReader readStream = new StreamReader( receiveStream, encode );
Console.WriteLine("\r\nResponse stream received.");

Char[] read = new Char[256];
            // Reads 256 characters at a time.    
int count = readStream.Read( read, 0, 256 );
Console.WriteLine("HTML...\r\n");
while (count > 0) 
    {
                    // Dumps the 256 characters on a string and displays the string to the console.
        String str = new String(read, 0, count);
        Console.Write(str);
        count = readStream.Read(read, 0, 256);
    }
Console.WriteLine("");
// Releases the resources of the response.
myHttpWebResponse.Close();
// Releases the resources of the Stream.
readStream.Close();