Exemple #1
0
        static void SendAsset(HttpListenerResponse rp, string assetName)
        {
            rp.AddHeader("Content-Type", Mime.GetType(assetName));
            Stream os = rp.OutputStream;

            byte[] asset = null;
            if (cachedAssets.TryGetValue(assetName, out asset))
            {
                rp.ContentLength64 = asset.LongLength;
                os.Write(asset, 0, asset.Length);
                os.Close();
            }
        }
        void SendFriendlyHtmlPage(HttpListenerResponse response)
        {
            var message = getFriendlyHtmlPageContent();
            var headers = getFriendlyHtmlPageHeaders();

            response.AddHeader("Content-Type", "text/html; charset=utf-8");
            foreach (var header in headers)
            {
                response.AddHeader(header.Key, header.Value);
            }

            // This could fail if the client terminates the connection and we attempt to write to it
            // Disposing the StreamWriter will close the stream - it owns the stream
            using (var writer = new StreamWriter(response.OutputStream, new UTF8Encoding(false))
            {
                NewLine = "\r\n"
            })
            {
                writer.WriteLine(message);
                writer.Flush();
            }
        }
Exemple #3
0
        public static void CreateResponse(this HttpListenerResponse response, HttpStatusCode statusCode,
                                          Stream contentStream, string contentType)
        {
            if (response == null)
            {
                throw new ArgumentNullException(nameof(response));
            }

            try
            {
                var    assemblyName  = Assembly.GetEntryAssembly().GetName();
                string serverName    = assemblyName.Name;
                string serverVersion = assemblyName.Version.ToString();

                response.StatusCode = (int)statusCode;
                response.AddHeader("Date", DateTime.UtcNow.ToString("R"));
                response.Headers.Remove("Server");
                response.AddHeader("Server", $"{serverName}/{serverVersion}");
                response.ContentType     = contentType;
                response.ContentLength64 = contentStream.Length;

                var buffer = new byte[1024 * 16];
                int nbytes;
                while ((nbytes = contentStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    response.OutputStream.Write(buffer, 0, nbytes);
                }

                response.OutputStream.Flush();
            }
            catch
            {
                response.StatusCode = (int)HttpStatusCode.InternalServerError;
            }
            finally
            {
                response.OutputStream.Close();
            }
        }
Exemple #4
0
        /// <summary>
        /// リクエスト時の処理を実行する
        /// </summary>
        /// <param name="result">結果</param>
        private static async void OnRequested(IAsyncResult result)
        {
            HttpListener clsListener = (HttpListener)result.AsyncState;

            if (!clsListener.IsListening)
            {
                return;
            }

            HttpListenerContext  context = clsListener.EndGetContext(result);
            HttpListenerRequest  req     = context.Request;
            HttpListenerResponse res     = context.Response;

            res.AddHeader("Access-Control-Allow-Origin", "*");  // どこからのリクエストでも受け取る
            res.AddHeader("Access-Control-Allow-Headers", "*"); // どこからのリクエストでも受け取る
            res.AddHeader("Access-Control-Allow-Methods", "*"); // どこからのリクエストでも受け取る
            try
            {
                await mapper.Execute(req, res);
            }
            catch (Exception ex)
            {
                // log.Error(ex.ToString());
            }
            finally
            {
                try
                {
                    if (null != res)
                    {
                        res.Close();
                    }
                }
                catch (Exception clsEx)
                {
                    // log.Error(clsEx.ToString());
                }
            }
        }
Exemple #5
0
 private void OnHttpResponse(HttpClientConnection connection, byte[] data, int offset, int count)
 {
     try
     {
         connection.TimeoutTimer.Dispose();
         HttpListenerResponse response = connection.Context.Response;
         response.ContentType = "application/octet-stream";
         if (data[offset] == 0x1f && data[offset + 1] == 0x8b && data[offset + 2] == 0x08 && data[offset + 3] == 0x00)
         {
             response.AddHeader("Content-Encoding", "gzip");
         }
         response.AddHeader("Access-Control-Allow-Origin", "*");
         response.ContentLength64 = count;
         Stream output = response.OutputStream;
         output.Write(data, offset, count);
         output.Close();
         connection.Close();
     }
     catch
     {
     }
 }
Exemple #6
0
        internal static void JourneysDelete(HttpListenerRequest request, HttpListenerResponse response)
        {
            // in: CarID, StartPosID, EndPosId
            // out: CarID, StartPosID, EndPosId
            // action: render really delete HTML
            response.AddHeader("Content-Type", "text/html; charset=utf-8");
            StringBuilder sb = new StringBuilder();
            int journeyID = Convert.ToInt32(GetUrlParameterValue(request, "id"), Tools.ciEnUS);
            try
            {
                using (MySqlConnection con = new MySqlConnection(DBHelper.DBConnectionstring))
                {
                    con.Open();
                    using (MySqlCommand cmd = new MySqlCommand(@"
SELECT
    journeys.name,
    cars.display_name,
    tripStart.Start_address,
    tripEnd.End_address
FROM
    journeys,
    cars,
    trip tripStart,
    trip tripEnd
WHERE
    journeys.CarID = cars.Id
    AND journeys.StartPosID = tripStart.StartPosID
    AND journeys.EndPosID = tripEnd.EndPosID
    AND journeys.ID = @journeyID", con))
                    {
                        cmd.Parameters.AddWithValue("@journeyID", journeyID);
                        Tools.DebugLog(cmd);
                        MySqlDataReader dr = SQLTracer.TraceDR(cmd);
                        if (dr.Read())
                        {
                            sb.Append($@"
<tr><td>{WebUtility.HtmlEncode(TEXT_LABEL_REALLY_DELETE)}&nbsp;{WebUtility.HtmlEncode(dr[0].ToString())}&nbsp;({WebUtility.HtmlEncode(dr[1].ToString())})&nbsp;-&nbsp;{WebUtility.HtmlEncode(dr[2].ToString())}{WebUtility.HtmlEncode("-->")}{WebUtility.HtmlEncode(dr[3].ToString())}?</td>
<td><form action=""{EndPoints["JourneysDeleteDelete"]}""><input type=""hidden"" name=""id"" value=""{journeyID}""><button type=""submit"">{WebUtility.HtmlEncode(TEXT_BUTTON_DELETE_DELETE)}</button></form></td>
");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ex.ToExceptionless().FirstCarUserID().Submit();
                Logfile.Log(ex.ToString());
                sb.Append(ex.ToString());
            }
            WriteString(response, html1 + sb.ToString() + html2);
        }
Exemple #7
0
 private string HandleRequest(HttpListenerRequest request, HttpListenerResponse response, string data)
 {
     if (request.RawUrl.StartsWith("/FormHttpServer/"))
     {
         // /FormHttpServer/CheckAccount            { "name" : "admin", "password" : "123456" }
         return(HttpServer.HandleObjectMethod(request, request.RawUrl, data, this).Result);
     }
     else
     {
         if (request.HttpMethod == "GET")
         {
             if (returnWeb.ContainsKey(request.RawUrl))
             {
                 response.AddHeader("Content-type", $"{comboBox1.SelectedItem.ToString( )}; charset=utf-8");
                 return(returnWeb[request.RawUrl]);
             }
             else
             {
                 response.AddHeader("Content-type", $"{comboBox1.SelectedItem.ToString( )}; charset=utf-8");
                 // return HttpServer.HandleObjectMethod( request, data, this );
                 return("123456");
             }
         }
         else if (request.HttpMethod == "POST")
         {
             // POST示例,在data中可以上传复杂的数据,长度不限制的
             if (postWeb.ContainsKey(request.RawUrl))
             {
                 response.AddHeader("Content-type", $"{comboBox1.SelectedItem.ToString( )}; charset=utf-8");
                 return(postWeb[request.RawUrl]);
             }
         }
         else
         {
         }
         return(string.Empty);
     }
 }
        private void SendHeaders()
        {
            if (_HeadersSent)
            {
                throw new IOException("Headers already sent.");
            }

            _Response.ContentLength64   = ContentLength;
            _Response.StatusCode        = StatusCode;
            _Response.StatusDescription = GetStatusDescription(StatusCode);
            _Response.SendChunked       = ChunkedTransfer;
            _Response.ContentType       = ContentType;

            if (Headers != null && Headers.Count > 0)
            {
                foreach (KeyValuePair <string, string> header in Headers)
                {
                    if (String.IsNullOrEmpty(header.Key))
                    {
                        continue;
                    }
                    _Response.AddHeader(header.Key, header.Value);
                }
            }

            if (_Settings.Headers != null)
            {
                foreach (KeyValuePair <string, string> header in _Settings.Headers)
                {
                    if (!Headers.Any(h => h.Key.ToLower().Equals(header.Key.ToLower())))
                    {
                        _Response.AddHeader(header.Key, header.Value);
                    }
                }
            }

            _HeadersSent = true;
        }
Exemple #9
0
        private void ProcessContext(HttpListenerContext context)
        {
            HttpListenerRequest request = context.Request;
            string httpMethod           = request.HttpMethod;
            string requestBody          = string.Empty;

            if (string.Compare(httpMethod, "POST", StringComparison.OrdinalIgnoreCase) == 0)
            {
                int    totalBytesRead = 0;
                byte[] bodyData       = new byte[request.ContentLength64];
                while (totalBytesRead < request.ContentLength64)
                {
                    totalBytesRead += request.InputStream.Read(bodyData, totalBytesRead, (int)request.ContentLength64 - totalBytesRead);
                }

                requestBody = Encoding.UTF8.GetString(bodyData);
            }

            // Obtain a response object.
            HttpListenerResponse response = context.Response;
            ServerResponse       result   = this.DispatchRequest(request.Url, httpMethod, requestBody);

            if (result.StatusCode == HttpStatusCode.SeeOther)
            {
                response.AddHeader("Location", request.Url.AbsoluteUri + "/" + result.ReturnedResponse.Value.ToString());
                result.ReturnedResponse.Value = string.Empty;
            }

            string responseString = result.ReturnedResponse.ToJson();

            // Construct a response.
            byte[] buffer = Encoding.UTF8.GetBytes(responseString);
            response.ContentType       = result.ContentType;
            response.StatusCode        = (int)result.StatusCode;
            response.StatusDescription = result.StatusCode.ToString();

            // Get a response stream and write the response to it.
            response.ContentLength64 = buffer.Length;
            Stream output = response.OutputStream;

            output.Write(buffer, 0, buffer.Length);

            // We must close the output stream.
            output.Close();

            if (request.Url.AbsolutePath.ToUpperInvariant().Contains(ShutdownUrlFragment))
            {
                this.OnShutdownRequested(new EventArgs());
            }
        }
Exemple #10
0
        private HttpStatusCode SendOkResponse(FileReadResults fileReadResults)
        {
            _response.StatusCode = (int)HttpStatusCode.OK;
            _response.Headers.Add(HttpResponseHeader.ContentType, GetContentTypeByFileExtension(fileReadResults.FileExtension));
            _response.Headers.Add(HttpResponseHeader.Date, DateTime.Now.ToLongDateString());
            _response.AddHeader("content-disposition", $"attachment;filename={fileReadResults.FileName}");

            var buffer = fileReadResults.FileBytes;

            _context.Response.ContentLength64 = buffer.Length;
            _context.Response.OutputStream.Write(buffer, 0, buffer.Length);

            return(HttpStatusCode.OK);
        }
Exemple #11
0
        public static void WriteResult(this HttpListenerResponse response, HttpStatusCode statusCode, string text)
        {
            response.StatusCode = (int)statusCode;

            response.AddHeader("Charset", Encoding.UTF8.WebName);

            response.ContentEncoding = Encoding.UTF8;

            var bytes = Encoding.UTF8.GetBytes(text);

            response.ContentLength64 = bytes.LongLength;

            response.OutputStream.Write(bytes, 0, bytes.Length);
        }
Exemple #12
0
        private void Debug_TeslaAPI(string path, HttpListenerRequest request, HttpListenerResponse response)
        {
            int position = path.LastIndexOf('/');

            if (position > -1)
            {
                path = path.Substring(position + 1);
                if (path.Length > 0 && WebHelper.TeslaAPI_Commands.TryGetValue(path, out string TeslaAPIJSON))
                {
                    response.AddHeader("Content-Type", "application/json");
                    WriteString(response, TeslaAPIJSON);
                }
            }
        }
 private void HeyListen(HttpAuthenticationService httpAuth)
 {
     using (HttpListener listener = new HttpListener())
     {
         listener.Prefixes.Add(Config.HttpPrefix);
         listener.AuthenticationSchemes = AuthenticationSchemes.Basic;
         listener.Start();
         while (true)
         {
             HttpListenerContext       context  = listener.GetContext();
             HttpListenerBasicIdentity identity = (HttpListenerBasicIdentity)context.User.Identity;
             if (identity == null || !httpAuth.Authenticate(identity.Name, identity.Password))
             {
                 HttpListenerResponse authResponse = context.Response;
                 authResponse.AddHeader("WWW-Authenticate", "Basic");
                 authResponse.StatusCode = (int)HttpStatusCode.Unauthorized;
                 using (StreamWriter writer = new StreamWriter(authResponse.OutputStream))
                 {
                     writer.Write("NO!");
                     writer.Flush();
                 }
                 continue;
             }
             var userId  = Helper.GetUserId(identity.Name);
             var guildId = Helper.GetGuildId(identity.Name);
             HttpListenerRequest request = context.Request;
             string command;
             using (StreamReader reader = new StreamReader(request.InputStream))
             {
                 command = reader.ReadToEnd();
             }
             HttpListenerResponse response = context.Response;
             string responseString;
             try
             {
                 responseString = HandleHttpCommand(command, userId, guildId);
             }
             catch (Exception ex)
             {
                 responseString      = ex.ToString();
                 response.StatusCode = (int)HttpStatusCode.InternalServerError;
             }
             using (StreamWriter writer = new StreamWriter(response.OutputStream))
             {
                 writer.Write(responseString);
                 writer.Flush();
             }
         }
     }
 }
Exemple #14
0
 public static void SendResponse(HttpListenerResponse response, string pluginName, string content)
 {
     CoreManager.ServerCore.GetStandardOut().PrintDebug("WebAdmin Response [" + pluginName + "]: " + content);
     byte[] buffer = Encoding.UTF8.GetBytes(content);
     response.StatusCode        = (int)HttpStatusCode.OK;
     response.StatusDescription = "OK";
     response.ContentType       = "text/html; charset=UTF-8";
     response.ContentLength64   = buffer.Length;
     response.ContentEncoding   = Encoding.UTF8;
     response.AddHeader("plugin-name", pluginName);
     response.OutputStream.Write(buffer, 0, buffer.Length);
     response.OutputStream.Close();
     response.Close();
 }
Exemple #15
0
        private void ManageRequests()
        {
            HttpListenerContext  context  = listener.GetContext();
            HttpListenerRequest  request  = context.Request;
            HttpListenerResponse response = context.Response;

            response.AddHeader("Access-Control-Allow-Origin", "*");

            HTTPResponse httpResponse = null;
            string       responseStr  = MatchRequest(request, ref httpResponse);

            HTTPResponse.AddHTTPResponseToResponse(httpResponse, ref response);
            SendResponse(response, responseStr);
        }
        private static void SendSelectableOptions(HttpListenerResponse Response, string returnOptions)
        {
            Response.StatusCode        = (int)HttpStatusCode.Accepted;
            Response.StatusDescription = "OK";
            Response.SendChunked       = false;
            Response.AddHeader("Content-Disposition", "text/plain");

            byte[] buffer = Encoding.UTF8.GetBytes(returnOptions);
            Response.ContentLength64 = buffer.Length;
            Stream output = Response.OutputStream;

            output.Write(buffer, 0, buffer.Length);
            output.Close();
        }
Exemple #17
0
        public async void file(string filePath)
        {
            if (!File.Exists(filePath))
            {
                send(StaticTemplates.NoFoundTemplate(filePath), 404, "text/html");
                return;
            }
            try
            {
                HttpListenerResponse response = context.Response;
                response.KeepAlive          = true;
                response.SendChunked        = true;
                context.Response.StatusCode = (int)HttpStatusCode.OK;
                string mime;
                var    stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
                response.ContentType     = ServerHelpers.mimeTypesMap.TryGetValue(Path.GetExtension(filePath), out mime) ? mime : "undefined";
                response.ContentLength64 = stream.Length;
                response.AddHeader("Accept-Ranges", "bytes");
                response.AddHeader("Date", DateTime.Now.ToString("r"));
                response.AddHeader("Last-Modified", System.IO.File.GetLastWriteTime(filePath).ToString("r"));
                response.AddHeader("Content-Range", string.Format("bytes {0}-{1}/{2}", 0, Convert.ToInt32(stream.Length) - 1, Convert.ToInt32(stream.Length)));
                response.ContentLength64 = stream.Length;

                await stream.CopyToAsync(context.Response.OutputStream);

                await stream.FlushAsync();

                response.Close();
            }
            catch (Exception ex)
            {
                if (JintAddons.debug)
                {
                    Log.Error(ex.Message + " " + ex.StackTrace);
                }
            }
        }
        public HttpListenerResponse HandleStaticRequest()
        {
            string filename = Path.Combine(directory, request.Url.Segments[1]);

            if (File.Exists(filename))
            {
                try
                {
                    Stream input = new FileStream(filename, FileMode.Open);

                    response.ContentType     = "text/html";
                    response.ContentLength64 = input.Length;
                    response.AddHeader("Date", DateTime.Now.ToString("r"));
                    response.AddHeader("Last-Modified", File.GetLastWriteTime(filename).ToString("r"));

                    byte[] buffer = new byte[1024 * 32];
                    int    nbytes;
                    while ((nbytes = input.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        response.OutputStream.Write(buffer, 0, nbytes);
                    }
                    input.Close();
                    response.OutputStream.Flush();

                    response.StatusCode = (int)HttpStatusCode.OK;
                }
                catch (Exception ex)
                {
                    response.StatusCode = (int)HttpStatusCode.InternalServerError;
                }
            }
            else
            {
                response.StatusCode = (int)HttpStatusCode.NotFound;
            }
            return(response);
        }
        public static async Task CopyFromAsync(this HttpListenerResponse response, HttpResponseMessage message,
                                               IContentProcessor contentProcessor)
        {
            response.StatusCode = (int)message.StatusCode;
            foreach (var httpResponseHeader in message.Headers.Where(header => !Filter.Contains(header.Key)))
            {
                foreach (var value in httpResponseHeader.Value)
                {
                    response.AddHeader(httpResponseHeader.Key, value);
                }
            }
            foreach (var httpResponseHeader in message.Content.Headers.Where(header => !Filter.Contains(header.Key)))
            {
                foreach (var value in httpResponseHeader.Value)
                {
                    response.AddHeader(httpResponseHeader.Key, value);
                }
            }
            response.SendChunked = false;
            response.KeepAlive   = false;

            var bytes = await message.Content.ReadAsByteArrayAsync();

            if (bytes.Length <= 0)
            {
                return;
            }

            if (contentProcessor != null)
            {
                bytes = contentProcessor.Process(bytes, message.Content.Headers.ContentType,
                                                 message.RequestMessage.RequestUri);
            }

            response.ContentLength64 = bytes.Length;
            await response.OutputStream.WriteAsync(bytes, 0, bytes.Length);
        }
Exemple #20
0
        private void ProcessRequest(HttpListenerContext context)
        {
            var responseString = "";
            int statuscode     = 200;

            try
            {
                var body = JsonConvert.DeserializeObject <PlayerRequest>(new StreamReader(context.Request.InputStream).ReadToEnd());
                switch (context.Request.HttpMethod)
                {
                case "GET":
                    responseString = JsonConvert.SerializeObject(ProcessGet(body));
                    break;

                case "POST":
                    responseString = JsonConvert.SerializeObject(ProcessPost(body));
                    break;
                }
            }
            catch (Exception ex)
            {
                responseString = ex.Message;
                statuscode     = 500;
            }
            HttpListenerResponse response = context.Response;

            response.AddHeader("Access-Control-Allow-Origin", "*");
            response.AddHeader("Access-Control-Allow-Headers", "*");
            response.AddHeader("Access-Control-Allow-Methods", "*");
            response.StatusCode  = statuscode;
            response.ContentType = "text/plain";

            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
            response.ContentLength64 = buffer.Length;
            System.IO.Stream output = response.OutputStream;
            output.Write(buffer, 0, buffer.Length);
        }
Exemple #21
0
        static async Task Main(string[] args)
        {
            try
            {
                if (args.Length > 1)
                {
                    ParseArgs(args);
                }

                Console.WriteLine(string.Format("Tally Localhost Connector | Version: {0}", version));

                HttpListener httpListener = new HttpListener();
                httpListener.Prefixes.Add(string.Format("http://localhost:{0}/", port));
                httpListener.Start();
                Console.WriteLine(string.Format("Listener started on http://localhost:{0}", port));
                while (true)
                {
                    HttpListenerContext context = httpListener.GetContext();
                    HttpListenerRequest req     = context.Request;
                    using (StreamReader sr = new StreamReader(req.InputStream))
                    {
                        string payload           = sr.ReadToEnd();
                        HttpListenerResponse res = context.Response;
                        if (!IsTallyRunning())
                        {
                            res.StatusCode = 404;
                        }
                        else
                        {
                            string content = await FetchTallyData(payload);

                            res.AddHeader("Access-Control-Allow-Origin", "*");
                            res.StatusCode = 200;
                            byte[] buff = Encoding.UTF8.GetBytes(content);
                            res.ContentLength64 = buff.Length;
                            res.ContentType     = "text/plain";
                            res.ContentEncoding = Encoding.UTF8;
                            res.OutputStream.Write(buff, 0, buff.Length);
                        }
                        res.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw ex;
            }
        }
    void WriteFile(HttpListenerContext ctx, string path)
    {
        HttpListenerResponse response = ctx.Response;

        httpResponses.Add(response);

        using (FileStream fs = File.OpenRead(path))
        {
            string filename = Path.GetFileName(path);
            string mime;

            //Set the type of media to play
            if (!mimeDic.TryGetValue(Path.GetExtension(filename), out mime))
            {
                mime = "application/octet-stream";
            }


            ctx.Response.ContentType = mime;
            response.ContentLength64 = fs.Length;

            //Stream the File
            response.SendChunked = true;

            //Enable Media Seek(Rewind/Fastforward)
            response.StatusCode = 206;
            response.AddHeader("Content-Range", "bytes 0-" + (fs.Length - 1) + "/" + fs.Length);
            //According to Content Range
            //https://greenbytes.de/tech/webdav/rfc7233.html#header.content-range


            //Send data to the connected client
            byte[] buffer = new byte[64 * 1024];
            int    read;
            using (BinaryWriter bw = new BinaryWriter(response.OutputStream))
            {
                while ((read = fs.Read(buffer, 0, buffer.Length)) > 0)
                {
                    bw.Write(buffer, 0, read);
                    bw.Flush(); //seems to have no effect
                }
                bw.Close();
            }

            response.StatusCode        = (int)HttpStatusCode.OK;
            response.StatusDescription = "OK";
            response.OutputStream.Close();
        }
    }
Exemple #23
0
        private void Flush(HttpListenerRequest req, HttpListenerResponse res, byte[] buffer)
        {
            res.ContentType = "text/plain";

            if (buffer == null || buffer.Length == 0)
            {
                res.Close();
                Logger.Info($"Response {res.StatusCode}: Length=0");
                return;
            }

            var statusCode = res.StatusCode;

            // 接收 gzip 编码
            if (req.Headers != null && req.Headers.Get("Accept-Encoding") != null &&
                req.Headers.Get("Accept-Encoding").Contains("gzip"))
            {
                Logger.Info($"Client accepts GZip encoding");

                res.AddHeader("Content-Encoding", "gzip");
                MemoryStream memory = null;
                try
                {
                    memory = new MemoryStream();
                    using (var stream = new GZipStream(memory, CompressionMode.Compress, false))
                    {
                        stream.Write(buffer, 0, buffer.Length);
                    }
                    buffer = memory.ToArray();
                }
                finally
                {
                    if (memory != null)
                    {
                        memory.Dispose();
                    }
                }

                Logger.Info("GZip complete");
            }

            var length = res.ContentLength64 = buffer.LongLength;

            res.OutputStream.Write(buffer, 0, (int)length);
            res.OutputStream.Flush();
            res.Close();

            Logger.Info($"Response {statusCode}: Length={length}");
        }
 private string HandleRequest(HttpListenerRequest request, HttpListenerResponse response, string data)
 {
     if (request.HttpMethod == "GET")
     {
         if (returnWeb.ContainsKey(request.RawUrl))
         {
             response.AddHeader("Content-type", $"Content-Type: {comboBox1.SelectedItem.ToString( )}; charset=utf-8");
             return(returnWeb[request.RawUrl]);
         }
     }
     else if (request.HttpMethod == "POST")
     {
         // POST示例,在data中可以上传复杂的数据,长度不限制的
         if (postWeb.ContainsKey(request.RawUrl))
         {
             response.AddHeader("Content-type", $"Content-Type: {comboBox1.SelectedItem.ToString( )}; charset=utf-8");
             return(postWeb[request.RawUrl]);
         }
     }
     else
     {
     }
     return(string.Empty);
 }
Exemple #25
0
        public void ExportBlockedZones(HttpListenerResponse response)
        {
            IReadOnlyList <AuthZoneInfo> zoneInfoList = _dnsWebService.DnsServer.BlockedZoneManager.ListZones();

            response.ContentType = "text/plain";
            response.AddHeader("Content-Disposition", "attachment;filename=BlockedZones.txt");

            using (StreamWriter sW = new StreamWriter(new BufferedStream(response.OutputStream)))
            {
                foreach (AuthZoneInfo zoneInfo in zoneInfoList)
                {
                    sW.WriteLine(zoneInfo.Name);
                }
            }
        }
Exemple #26
0
        public void Handle(RequestData data)
        {
            HttpListenerResponse serverResponse = data.Context.Response;

            Log.Info($"Authentication requested from client at {data.Context.Request.RemoteEndPoint}");
            serverResponse.StatusCode  = (int)HttpStatusCode.OK;
            serverResponse.ContentType = "text/plain";
            serverResponse.AddHeader("Content-Encoding", "deflate");
            EftClient client = data.Client;

            byte[] messageBytes = ZlibStream.CompressString(AuthenticationService.Authenticate(ref client, data.Body));
            serverResponse.OutputStream.Write(messageBytes, 0, messageBytes.Length);
            serverResponse.SetCookie(new Cookie("PHPSESSID", client.UniqueSession));;
            serverResponse.Close();
        }
Exemple #27
0
        private Stream GetOutputStream(HttpListenerRequest request, HttpListenerResponse response)
        {
            var ostream = response.OutputStream;

            if (Compress)
            {
                string acceptEncoding = request.Headers["Accept-Encoding"];
                if (acceptEncoding != null)
                {
                    acceptEncoding = acceptEncoding.ToLowerInvariant();
                    if (acceptEncoding.Contains("gzip"))
                    {
                        response.AddHeader("Content-Encoding", "gzip");
                        ostream = new GZipStream(ostream, CompressionMode.Compress);
                    }
                    else if (acceptEncoding.Contains("deflate"))
                    {
                        response.AddHeader("Content-Encoding", "deflate");
                        ostream = new DeflateStream(ostream, CompressionMode.Compress);
                    }
                }
            }
            return(ostream);
        }
Exemple #28
0
        async Task WriteResponse(HttpResponse response, HttpListenerResponse httpListenerResponse)
        {
            httpListenerResponse.StatusCode  = (int)response.StatusCode;
            httpListenerResponse.ContentType = response.ContentType;

            foreach (var header in response.Headers)
            {
                httpListenerResponse.AddHeader(header.Key, header.Value);
            }

            using (var output = httpListenerResponse.OutputStream)
            {
                await response.Stream(output);
            }
        }
Exemple #29
0
 /// <summary>
 /// Write the response to outgoing stream.
 /// </summary>
 /// <param name="text"></param>
 public void write(string text) {
     // First request requires syncing headers
     if (!this.isHeaderSent) {
         response.Headers.Clear();
         foreach (string key in headers.Keys)
         {
             response.AddHeader(key, headers[key].ToString());
         }
     }
     // Write to outgoing stream
     byte[] buffer = Encoding.UTF8.GetBytes(text);
     response.OutputStream.Write(buffer, 0, buffer.Length);
     response.OutputStream.Flush();
     this.isHeaderSent = true;
 }
Exemple #30
0
 private void SendHeader(HttpListenerRequest request, HttpListenerResponse response)
 {
     response.ContentType = "text/plain";
     if (P3P)
     {
         response.AddHeader("P3P",
                            "CP=\"CAO DSP COR CUR ADM DEV TAI PSA PSD IVAi IVDi " +
                            "CONi TELo OTPi OUR DELi SAMi OTRi UNRi PUBi IND PHY ONL " +
                            "UNI PUR FIN COM NAV INT DEM CNT STA POL HEA PRE GOV\"");
     }
     if (CrossDomain)
     {
         string origin = request.Headers["Origin"];
         if (string.IsNullOrEmpty(origin) || origin == "null")
         {
             response.AddHeader("Access-Control-Allow-Origin", "*");
         }
         else if (origins.Count == 0 || origins.ContainsKey(origin))
         {
             response.AddHeader("Access-Control-Allow-Origin", origin);
             response.AddHeader("Access-Control-Allow-Credentials", "true");
         }
     }
 }