Csharp/C Sharp/Network/Web Request Response

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Get HTTP Request Headers

using System;
using System.IO;
using System.Net;
public class TryHttpRequest {
  public static void Main(String [] args) {
    HttpWebRequest request =(HttpWebRequest)WebRequest.Create("http://www.nfex.ru");
    HttpWebResponse response =(HttpWebResponse)request.GetResponse();
    request.Accept = "text/plain";
    Console.WriteLine("Request header count: {0}",request.Headers.Count);
    WebHeaderCollection header = request.Headers;
    for (int i = 0; i < header.Count; i++)
      Console.WriteLine("   {0} : {1}",header.GetKey(i), header[i]);
      
  }
}


Get HTTP Response headers

using System;
using System.IO;
using System.Net;
public class TryHttpRequest {
  public static void Main(String [] args) {
    HttpWebRequest request =(HttpWebRequest)WebRequest.Create("http://www.nfex.ru");
    HttpWebResponse response =(HttpWebResponse)request.GetResponse();
    request.Accept = "text/plain";
    
    Console.WriteLine("Response headers");
    Console.WriteLine("  Protocol version: {0}",                                             response.ProtocolVersion);
    Console.WriteLine("  Status code: {0}",response.StatusCode);
    Console.WriteLine("  Status description: {0}",response.StatusDescription);
    Console.WriteLine("  Content encoding: {0}",response.ContentEncoding);
    Console.WriteLine("  Content length: {0}",response.ContentLength);
    Console.WriteLine("  Content type: {0}",response.ContentType);
    Console.WriteLine("  Last Modified: {0}",response.LastModified);
    Console.WriteLine("  Server: {0}", response.Server);
    Console.WriteLine("  Length using method: {0}\n",response.GetResponseHeader("Content-Length"));
  
  }
}


Uses WebRequest and WebResponse. Tests use HTTP and the file protocol

using System;
using System.IO;
using System.Net;
public class TryWebRequest {
  public static void Main(String [] args) {
    WebRequest request = WebRequest.Create("http://www.nfex.ru");
    WebResponse response = request.GetResponse();
    Console.WriteLine("Content length: {0}", response.ContentLength);
    Console.WriteLine("Content type: {0}\n", response.ContentType);
    Console.WriteLine("Request header count: {0}", request.Headers.Count);
    WebHeaderCollection header = request.Headers;
    for (int i = 0; i < header.Count; i++)
      Console.WriteLine("{0} : {1}", header.GetKey(i), header[i]);
    Console.WriteLine();
    StreamReader input = new StreamReader(response.GetResponseStream());
    Console.WriteLine(input.ReadToEnd());
    input.Close();
  }
}