2017-09-23 134 views
0

这里是我的C#代码发送到服务器的请求:C#不能的GetResponse()得到响应头

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天)...

+0

您需要访问'响应Headers'性能输出。 https://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.headers(v=vs.110).aspx –

回答

0

您的代码正在为我工​​作。我能够打印头在响应使用以下行

Console.WriteLine(response.Headers); 

这里是头

enter image description here

+0

Yaaaaaaaaaaaaaaaay !!!多谢老兄!有效。但它不适用于请求的PUT方法。它添加此字符串时使用PUT方法:ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; –