c#无法从GetResponse()获取响应头

时间:2017-09-23 10:22:50

标签: c# getresponse

这是我的c#代码,它向服务器发送请求:

    try
{
    string url = "https://example.com/";
    string json = "thisisanexample";
    byte[] data = Encoding.UTF8.GetBytes(json);
    System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
    request.ContentLength = data.Length;
    request.KeepAlive = true;
    request.Accept = "application/json, text/plain, */*";
    request.Headers.Add("Accept-Language", "en-US,en;q=0.8");
    request.Headers.Add("Accept-Encoding", "gzip, deflate, br");
    request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
    ServicePointManager.Expect100Continue = false;
    Stream dataStream = request.GetRequestStream ();  
    // Write the data to the request stream.  
    dataStream.Write (data, 0, data.Length);  
    // Close the Stream object.  
    dataStream.Close ();  
    // Get the response.  
    WebResponse response = request.GetResponse();  
    // Display the status.  
    Console.WriteLine (((HttpWebResponse)response).StatusDescription);  
    // Get the stream containing content returned by the server.  
    dataStream = response.GetResponseStream ();  
    // Open the stream using a StreamReader for easy access.  
    StreamReader reader = new StreamReader (dataStream);  
    // Read the content.  
    string responseFromServer = reader.ReadToEnd();  
    // Display the content.  
    Console.WriteLine (responseFromServer);  
    // Clean up the streams.  
    reader.Close ();  
    dataStream.Close ();  
    response.Close (); 
    return responseFromServer;
}
catch (Exception e)
{
    return "ERROR:" + e.Message;
}

问题是没有获得响应标头...我试图使用GetResponse.Headers(),但它没有用...请帮助我(我已经厌倦了这段代码5天了) ...

1 个答案:

答案 0 :(得分:0)

你的代码对我有用。我可以使用以下行

在响应中打印标题
Console.WriteLine(response.Headers);

这是标题

的输出

enter image description here