locked
C# HTTP request/response

    Question

  • Hello everyone,

     


    I need to build up using C# HTTP Server (HTTP Listener, which could parse various HTTP fields, like post data and return response) and I also need to get an HTTP client which could package various HTTP fields (like URL, post data, etc.).

     

    Are there any sample codes to recommend? I searched MSDN, failed to find any complete client and server samples. I have searched some other samples, which is built on TCP listener, and manually package/unpackage from TCP other than HTTP package level.

     


    thanks in advance,
    George

     

    Wednesday, April 02, 2008 12:04 PM

Answers

All replies

  • For client, WebClient should do everything you need. See MSDN:

     

    http://msdn2.microsoft.com/en-us/library/system.net.webclient(VS.80).aspx

     

    For server, easiest (for simple client/server) would be a "handler" (i.e. an ashx page) in asp.net; alternatively you can use HttpListener to create a basic server that can respond to requests; again see MSDN:

     

    http://msdn2.microsoft.com/en-us/library/system.net.httplistener.aspx

     

    Wednesday, April 02, 2008 12:13 PM
  • Code Snippet

    WebRequest request = WebRequest.Create("your url comes here with parameters and stuf like in IE");

    HttpWebResponse response = (HttpWebResponse)request.GetResponse();

    Stream dataStream = response.GetResponseStream();

    StreamReader reader = new StreamReader(dataStream);

    string responseFromServer = reader.ReadToEnd();

    reader.Close();

    dataStream.Close();

    response.Close();

     

     

    Wednesday, April 02, 2008 1:51 PM
  • Or...

     

    Code Snippet

    using (WebClient client = new WebClient())

    {

        string responseFromServer = client.DownloadString("your url comes here with parameters and stuf like in IE");

    }

     

    I know which I'll go for... WebClient also offers a range of other methods and overloads for most common cases, such as sending a body, talking to files, etc...

    Wednesday, April 02, 2008 2:07 PM
  • All of the replies are helpful, question answered.

     

     Marc Gravell wrote:

    For client, WebClient should do everything you need. See MSDN:

     

    http://msdn2.microsoft.com/en-us/library/system.net.webclient(VS.80).aspx

     

    For server, easiest (for simple client/server) would be a "handler" (i.e. an ashx page) in asp.net; alternatively you can use HttpListener to create a basic server that can respond to requests; again see MSDN:

     

    http://msdn2.microsoft.com/en-us/library/system.net.httplistener.aspx

     

     

     

    regards,

    George

    Monday, April 07, 2008 5:24 AM
  • what would be the best way to handle rendering a live map on a mobile device. it doesn't need web browser controls. recommendations?
    Tuesday, September 09, 2008 11:09 AM