none
HttpListenerResponse : write all headers response to file RRS feed

  • Question

  • Hello,

    The following code is used as a simple HTTP server. 

    It works. 

    It is a reference for a win32 HTTP server I'm developing. 

    How can I save the headers response this code is sending to the client ?

    Thank you,

    Zvika 

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Text;
    using System.IO;
    
    namespace HttpLstener
    {
        class Program
        {
            static void Main(string[] args)
            {
                var web = new HttpListener();
                string FileName=null, FilePath=null;
    
                web.Prefixes.Add("http://*:8000/");
    
                Console.WriteLine("Listening..");
    
                web.Start();
    
                while (true)
                {
                    HttpListenerContext context = web.GetContext();
    
                    HttpListenerResponse response = context.Response;
                    HttpListenerRequest request = context.Request;
    
                    response.StatusCode = 200;
                    response.Headers.Add("Access-Control-Allow-Origin", "*");
    
                    if (request.RawUrl == "/" &&
                        request.RawUrl.Length == 1)
                        FileName = "/index.html";
                    else
                        FileName = request.RawUrl;
    
                    Console.WriteLine(FileName);
                    string Ext = Path.GetExtension(FileName);
                    if (Ext == ".html")
                        response.ContentType = "text/html";
                    else if (Ext == ".css")
                        response.ContentType = "text/css";
                    else if (Ext == ".js")
                        response.ContentType = "application/javascript";
                    else if (Ext == ".png")
                        response.ContentType = "image/png";
                    else if (Ext == ".ttf")
                        response.ContentType = "application/font-sfnt";
                    else if (Ext == ".ico")
                        response.ContentType = "image/vnd.microsoft.icon";
    
                    FilePath = "d:/dist/MY" + FileName;
                    byte[] buffer = File.ReadAllBytes(FilePath);
                    if (buffer.Length == 0)
                    {
                        Console.WriteLine("Failed to find: "+FileName);
                        break;
                    }
    
                    //response.ContentLength64 = buffer.Length;
                    Stream st = response.OutputStream;
                    //buffer.Length is the body length
                    st.Write(buffer, 0, buffer.Length);
    
                    response.Close();
                }
    
            }
        }
    }
    

    Wednesday, October 9, 2019 7:03 PM

Answers

  • The HttpListenerRequest has a header property.  You can loop through the headers and write them to the file.  The link shows how to write them in the console

    https://docs.microsoft.com/en-us/dotnet/api/system.net.httplistenerrequest.headers?view=netframework-4.8#System_Net_HttpListenerRequest_Headers

     
    • Marked as answer by Z. V Thursday, October 10, 2019 8:36 PM
    Thursday, October 10, 2019 9:59 AM
  • Hi Z.V,

    According to your question, I make a test on my side.

    Here's my code, and you can refer to and modify it.

    Server:

        class Program
        {
            static HttpListener web;
            static void Main(string[] args)
            {
                web = new HttpListener();
                web.Prefixes.Add("http://localhost:8080/");
                Console.WriteLine("Listening..");
                web.Start();
                web.BeginGetContext(Result, null);
                Console.WriteLine($"wait for client...");
                Console.ReadKey();
            }
            private static void Result(IAsyncResult ar)
            {
                web.BeginGetContext(Result, null);
                var context = web.EndGetContext(ar);
                var request = context.Request;
                var response = context.Response;
                context.Response.ContentType = "text/plain;charset=UTF-8";
                context.Response.ContentEncoding = Encoding.UTF8;
                response.Headers.Add("Access-Control-Allow-Origin", "*");
                response.StatusDescription = "200";
                response.StatusCode = 200;
    
                Console.WriteLine($"Headers: {response.Headers.ToString()}");
                string path = @"D:\test2.txt";
                FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                StreamWriter sw = new StreamWriter(fs);
                sw.WriteLine(response.Headers.ToString());
                sw.Flush();
                sw.Close();
                fs.Close();
    
                byte[] buffer = new byte[2048];
                if (request.HttpMethod == "POST" && request.InputStream != null)
                {
                    string filepath = @"D:\test.txt";
                    buffer = File.ReadAllBytes(filepath);
    
                    if (buffer.Length == 0)
                    {
                        Console.WriteLine("Failed to find file");
                    }
                }
                else
                {
                    // not post or data is null.
                }
                try
                {
                    using (var stream = response.OutputStream)
                    {
                        stream.Write(buffer, 0, buffer.Length);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"{ex.ToString()}");
                }
    
            }
        }

    Client:

            static void Main(string[] args)
            {
                string operation;
                do
                {
                    Console.WriteLine("send data to server");
                    string data = Console.ReadLine();
                    var webClient = new WebClient();
                    var url = "http://localhost:8080/";
                    var returnInfo = webClient.UploadData(url, Encoding.UTF8.GetBytes(data));
                    var str = Encoding.UTF8.GetString(returnInfo);
                    Console.WriteLine($"server message:{str}");
                    Console.WriteLine($"continue: y or n");
                    operation = Console.ReadLine();
                } while (operation == "y");
            }

    Result of server:

    Result of client:

    Result of text file:

    If I have any misunderstanding, please provide more information about the headers you want to save.

    Best Regards,

    Xingyu Zhao


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by Z. V Thursday, October 10, 2019 8:36 PM
    Thursday, October 10, 2019 10:11 AM
    Moderator

All replies

  • The HttpListenerRequest has a header property.  You can loop through the headers and write them to the file.  The link shows how to write them in the console

    https://docs.microsoft.com/en-us/dotnet/api/system.net.httplistenerrequest.headers?view=netframework-4.8#System_Net_HttpListenerRequest_Headers

     
    • Marked as answer by Z. V Thursday, October 10, 2019 8:36 PM
    Thursday, October 10, 2019 9:59 AM
  • Hi Z.V,

    According to your question, I make a test on my side.

    Here's my code, and you can refer to and modify it.

    Server:

        class Program
        {
            static HttpListener web;
            static void Main(string[] args)
            {
                web = new HttpListener();
                web.Prefixes.Add("http://localhost:8080/");
                Console.WriteLine("Listening..");
                web.Start();
                web.BeginGetContext(Result, null);
                Console.WriteLine($"wait for client...");
                Console.ReadKey();
            }
            private static void Result(IAsyncResult ar)
            {
                web.BeginGetContext(Result, null);
                var context = web.EndGetContext(ar);
                var request = context.Request;
                var response = context.Response;
                context.Response.ContentType = "text/plain;charset=UTF-8";
                context.Response.ContentEncoding = Encoding.UTF8;
                response.Headers.Add("Access-Control-Allow-Origin", "*");
                response.StatusDescription = "200";
                response.StatusCode = 200;
    
                Console.WriteLine($"Headers: {response.Headers.ToString()}");
                string path = @"D:\test2.txt";
                FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                StreamWriter sw = new StreamWriter(fs);
                sw.WriteLine(response.Headers.ToString());
                sw.Flush();
                sw.Close();
                fs.Close();
    
                byte[] buffer = new byte[2048];
                if (request.HttpMethod == "POST" && request.InputStream != null)
                {
                    string filepath = @"D:\test.txt";
                    buffer = File.ReadAllBytes(filepath);
    
                    if (buffer.Length == 0)
                    {
                        Console.WriteLine("Failed to find file");
                    }
                }
                else
                {
                    // not post or data is null.
                }
                try
                {
                    using (var stream = response.OutputStream)
                    {
                        stream.Write(buffer, 0, buffer.Length);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"{ex.ToString()}");
                }
    
            }
        }

    Client:

            static void Main(string[] args)
            {
                string operation;
                do
                {
                    Console.WriteLine("send data to server");
                    string data = Console.ReadLine();
                    var webClient = new WebClient();
                    var url = "http://localhost:8080/";
                    var returnInfo = webClient.UploadData(url, Encoding.UTF8.GetBytes(data));
                    var str = Encoding.UTF8.GetString(returnInfo);
                    Console.WriteLine($"server message:{str}");
                    Console.WriteLine($"continue: y or n");
                    operation = Console.ReadLine();
                } while (operation == "y");
            }

    Result of server:

    Result of client:

    Result of text file:

    If I have any misunderstanding, please provide more information about the headers you want to save.

    Best Regards,

    Xingyu Zhao


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by Z. V Thursday, October 10, 2019 8:36 PM
    Thursday, October 10, 2019 10:11 AM
    Moderator
  • Hi Ken, Xingyu,

    Thank you very much !

    Best regards,

    Zvika 

    Thursday, October 10, 2019 8:38 PM