Friday, June 3, 2011

HttpWebRequest and HttpWebresponse using for loop

Program:-

using System;

using System.Net;

using System.Collections;
using System.Collections.Generic;

using System.Linq;

using System.Text;


namespace Http
{
class Program
{
static void Main(string[] args)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://www.google.com");

HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Console.WriteLine("\n THE HEADERS THAT WERE RECEIVED IN THE RESPONSE:");
for (int i = 0; i < resp.Headers.Count; ++i)
Console.WriteLine("\n Header Name:{0},Value:{1}", resp.Headers.Keys[i], resp.Headers[i]);


resp.Close();
}
}
}


Output:-

IEnumerable Interface and HttpWebRequest/Response using foreach

Here in this program i have used both the concept of IEnumerable interface and foreach concept,each performing separate work.

1)Firstly,using IEnumerable Interface i have declared an array to define some properties of headers using GetEnumerator to create the object.Hereby using foreach to iterate it.It has been seen that to use foreach in such a context i had to define the IEnumerator/IEnumerable interface.

2)Secondly,i used foreach to illustrate the concept of HttpWebRequest and HttpWebResponse.

Program:

using System;
using System.Collections.Generic;
using System.Net;
using System.Collections;
using System.Linq;
using System.Text;

namespace sample
{
class Program
{
private string Name;
private string SetBy;
public Program( string name,string setby)
{
this.Name=name;
this.SetBy=setby;
}
public string NAME
{
get
{
return this.Name;
}
}
public override string ToString()
{
return "Name:" + this.Name.ToString() + "\nSetBy:" + SetBy;
}
}

class Http:IEnumerable,IEnumerator
{
ArrayList List=new ArrayList();
private int Position=-1;
public void AddContent(Program Prog)
{
List.Add(Prog);
}
public IEnumerator GetEnumerator()
{
return (IEnumerator)this;
}
public bool MoveNext()
{
if(Position < List.Count-1)
{
++Position;
return true;
}
return false;
}
public void Reset()
{
Position=-1;
}
public object Current
{
get{
return List[Position];
}
}



static void Main(string[] args)
{
Http List = new Http();
Program p1 = new Program("Accept", "Set by the Accept property");
Program p2 = new Program("Content-Length", "Set by the conenction property");
List.AddContent(p1);
List.AddContent(p2);
foreach (Program prg in List)
{
Console.WriteLine(prg);
}
Console.WriteLine("\nEnumerator Program creating object of IEnumerator");
IEnumerator WebEnumerator = List.GetEnumerator();
WebEnumerator.Reset();
while (WebEnumerator.MoveNext())
{
Console.WriteLine((Program)WebEnumerator.Current);
}

HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://www.google.com");

HttpWebResponse resp = (HttpWebResponse)req.GetResponse();


Console.WriteLine("\n THE HEADERS THAT WERE RECEIVED IN THE RESPONSE:");

foreach (var i in resp.Headers.AllKeys)
{
Console.WriteLine("\nHeader Name:{0},\tValue:{1}", i, resp.Headers[i]);

}

}
}
}

OUTPUT:-
1)


2)