【问题标题】:c# cannot getting response headers from GetResponse()c# 无法从 GetResponse() 获取响应头
【发布时间】:2017-09-23 10:22:50
【问题描述】:

这是我向服务器发送请求的 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 天) ...

【问题讨论】:

标签: c# getresponse


【解决方案1】:

您的代码对我有用。我可以使用以下行打印响应中的标题

Console.WriteLine(response.Headers);

这是标题的输出

【讨论】:

  • 耶啊啊啊啊啊啊啊啊!!!非常感谢老兄!有效。但它不适用于请求的 PUT 方法。添加此字符串时,它适用于 PUT 方法:ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
猜你喜欢
  • 2023-01-12
  • 2021-02-03
  • 2014-02-26
  • 2015-02-10
  • 1970-01-01
  • 2019-10-27
  • 1970-01-01
  • 2013-04-06
  • 1970-01-01
相关资源
最近更新 更多