private static async Task ServeDirectoryListingAsync(DirectoryInfo root, DirectoryInfo directory, HttpListenerResponse response) { StringBuilder listBuilder = new StringBuilder(); foreach (FileInfo file in directory.EnumerateFiles()) { String target = directory.IsSameDirectory(root) ? file.Name : Path.Combine(directory.Name, file.Name); listBuilder.AppendFormat("<li><a href=\"{0}\">{1}</a></li>", target, file.Name); } foreach (DirectoryInfo subDirectory in directory.EnumerateDirectories()) { String target = directory.IsSameDirectory(root) ? subDirectory.Name : Path.Combine(directory.Name, subDirectory.Name); listBuilder.AppendFormat("<li><a href=\"{0}\">{1}</a></li>", target, subDirectory.Name); } String htmlResponse = String.Format("<ul>{0}</ul>", listBuilder.ToString()); response.ContentType = "text/html"; response.ContentLength64 = htmlResponse.Length; response.AddHeader("Date", DateTime.Now.ToString("r")); response.StatusCode = (Int32)HttpStatusCode.OK; // Must be set before writing to OutputStream. using (StreamWriter writer = new StreamWriter(response.OutputStream)) { await writer.WriteAsync(htmlResponse).ConfigureAwait(false); } }
public void Map(Response response, HttpListenerResponse result) { result.StatusCode = response.StatusCode; response.Headers.ToList().ForEach(pair => result.AddHeader(pair.Key, pair.Value)); if (response.Body != null) { var content = Encoding.UTF8.GetBytes(response.Body); result.OutputStream.Write(content, 0, content.Length); } }
/* * Prepare Output Stream, using gzip if supported */ protected Stream PrepareOutputStream(HttpListenerRequest request, HttpListenerResponse response) { string accept = request.Headers.Get("Accept-Encoding"); Stream outputStream = response.OutputStream; if (accept != null && accept.Contains("gzip")) { response.AddHeader("Content-Encoding", "gzip"); outputStream = new GZipStream(response.OutputStream, CompressionMode.Compress); } return outputStream; }
public static async Task ResponseText(HttpListenerResponse response, string localFilePath, string contentType) { var text = File.ReadAllText(localFilePath); response.ContentType = contentType; response.ContentEncoding = Encoding.UTF8; response.AddHeader("Charset", Encoding.UTF8.WebName); var textBytes = Encoding.UTF8.GetBytes(text); response.ContentLength64 = textBytes.LongLength; await response.OutputStream.WriteAsync(textBytes, 0, textBytes.Length); }
public static void deserializeResponse(string response, HttpListenerResponse originalResponse) { var headerResponse = JsonConvert.DeserializeObject<HeaderRespons> (response); if (relayIdSet.Contains (headerResponse.rid)) relayIdSet.Remove (headerResponse.rid); originalResponse.StatusCode = headerResponse.statusCode; foreach (var h in headerResponse.headers) { if (HeaderUtil.isEndToEndHeader (h.Key)) originalResponse.AddHeader (h.Key, h.Value); } //originalResponse.OutputStream.Write (headerResponse.body, 0, headerResponse.body.Length); }
void PrepareContext(HttpListenerResponse tragetRsp, HttpWebResponse sourceRsp) { tragetRsp.ContentEncoding = Encoding.GetEncoding(sourceRsp.CharacterSet); tragetRsp.ContentType = sourceRsp.ContentType; foreach (string k in sourceRsp.Headers) foreach (string v in sourceRsp.Headers.GetValues(k)) { if (string.Equals(k, "Content-Length", StringComparison.OrdinalIgnoreCase)) continue; tragetRsp.AddHeader(k, v); } }
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(); }
public void WriteHeaders() { if (HeadersSent) { throw new InvalidOperationException("The headers have already been sent."); } _nativeResponse.Headers.Clear(); foreach (var header in Headers.Where(h => h.Key != "Content-Length")) { try { _nativeResponse.AddHeader(header.Key, header.Value); } catch (Exception ex) { if (_context != null) { _context.ServerErrors.Add(new Error { Message = ex.ToString() }); } } } HeadersSent = true; _nativeResponse.ContentLength64 = Headers.ContentLength.GetValueOrDefault(); // TODO: Enable streaming straight back to native response output sting // Guard against a possible HttpListenerException : The specified network name is no longer available try { _tempStream.WriteTo(_nativeResponse.OutputStream); } catch (HttpListenerException ex) { if (_context != null) { _context.ServerErrors.Add(new Error { Message = ex.ToString() }); } } }
public void SendResponse(HttpListenerRequest request, HttpListenerResponse response) { var stream = new FileLoader(request.Url.AbsolutePath).LoadStream(); response.ContentLength64 = stream.Length; response.SendChunked = false; response.ContentType = request.ContentType; response.AddHeader("Content-disposition", "attachment; filename=" + request.RawUrl.Remove(0, 1)); writeTo(stream, response.OutputStream); response.StatusCode = (int)HttpStatusCode.OK; response.StatusDescription = "OK"; stream.Close(); response.Close(); Console.WriteLine("200"); }
private static void ConvertNancyResponseToResponse(Response nancyResponse, HttpListenerResponse response) { foreach (var header in nancyResponse.Headers) { response.AddHeader(header.Key, header.Value); } foreach (var nancyCookie in nancyResponse.Cookies) { response.Cookies.Add(ConvertCookie(nancyCookie)); } response.ContentType = nancyResponse.ContentType; response.StatusCode = (int)nancyResponse.StatusCode; using (var output = response.OutputStream) { nancyResponse.Contents.Invoke(output); } }
public Ansver SaveInfo(HttpListenerRequest request, HttpListenerResponse response) { Stream inputStream = request.InputStream; Console.WriteLine("������ ����������� �����������"); Console.WriteLine("���������� ������ �� ������:"); string result = ""; int last; string uriPath = request.Url.AbsolutePath.Split('/')[2]; try { byte[] ansver = new byte[request.ContentLength64]; request.InputStream.Read(ansver, 0, (int)request.ContentLength64); result = Encoding.UTF8.GetString(ansver); Console.WriteLine(result); Directory.CreateDirectory(path + uriPath); List<string> allfiles = new List<string>(Directory.GetFiles(path + uriPath, "*.txt")); allfiles.Sort(); last = this.GetLast(allfiles); StreamWriter writer = new StreamWriter(path + uriPath + "/" + (last).ToString() + ".txt",false, Encoding.UTF8); writer.Write(result); Console.WriteLine("������ ���������."); writer.Close(); response.AddHeader("id", last.ToString()); response.StatusCode = (int) HttpStatusCode.Created; return new Ansver(null, response); } catch (Exception exception) { Console.WriteLine("������ ����������, ��������� ������: " + exception.Message); response.StatusCode = (int) HttpStatusCode.InternalServerError; return new Ansver(null, response); } }
public void SendZippedResponse(HttpListenerResponse response, ByteResponseData data) { response.AddHeader("Content-Encoding", "gzip"); response.ContentType = data.ContentType.GetValue(); byte[] buffer = data.Content; using (MemoryStream ms = new MemoryStream()) { using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress)) { zip.Write(buffer, 0, buffer.Length); } buffer = ms.ToArray(); } WriteAndFlushResponse(response, buffer); }
public void AddHeader(string name, string value) { response.AddHeader(name, value); }
public void AddLastModifiedAndExpires(HttpListenerResponse response, string lastModified, string expires) { response.AddHeader("Last-Modified", lastModified); response.AddHeader("Expires", expires); }
/// <summary> /// Adds a set of HTTP headers to an <see cref="HttpResponse"/> instance, /// taking care to set some headers to the appropriate properties of /// <see cref="HttpResponse" /> /// </summary> /// <param name="headers">The headers to add.</param> /// <param name="response">The <see cref="HttpListenerResponse"/> instance to set the appropriate values to.</param> private static void ApplyHeadersToResponse(HttpResponseHeaders headers, HttpListenerResponse response) { Requires.NotNull(headers, "headers"); Requires.NotNull(response, "response"); foreach (var header in headers) { switch (header.Key) { case "Content-Type": response.ContentType = header.Value.First(); break; // Add more special cases here as necessary. default: response.AddHeader(header.Key, header.Value.First()); break; } } }
static void PleaseAuthenticate(HttpListenerResponse Response) { Response.StatusCode = 401; Response.AddHeader("WWW-Authenticate", "Basic realm=\"Spacecraft Server\""); string response = @"<!DOCTYPE HTML PUBLIC {0}-//W3C//DTD HTML 4.01 Transitional//EN{0} {0}http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd{0}> <HTML> <HEAD> <TITLE>Error</TITLE> <META HTTP-EQUIV={0}Content-Type{0} CONTENT={0}text/html; charset=ISO-8859-1{0}> </HEAD> <BODY><H1>401 Unauthorized.</H1></BODY> </HTML>"; response = String.Format(response, "\""); byte[] bytes = ASCIIEncoding.ASCII.GetBytes(response); Response.OutputStream.Write(bytes, 0, bytes.Length); }
private static void ConvertNancyResponseToResponse(Response nancyResponse, HttpListenerResponse response) { foreach (var header in nancyResponse.Headers) { response.AddHeader(header.Key, header.Value); } foreach (var nancyCookie in nancyResponse.Cookies) { response.Headers.Add(HttpResponseHeader.SetCookie, nancyCookie.ToString()); } response.ContentType = nancyResponse.ContentType; response.StatusCode = (int)nancyResponse.StatusCode; //HACK:This can probably be done nicely with som tweeking. if (nancyResponse is EventStreamWriterResponse) { nancyResponse.Contents.Invoke(response.OutputStream); } else { using (var output = response.OutputStream) { nancyResponse.Contents.Invoke(output); } } }
private void SendJSON(HttpListenerResponse response) { string JSON = "{\"id\": 0, \"Text\": \"Sensor\", \"Children\": ["; nodeCount = 1; JSON += GenerateJSON(root); JSON += "]"; JSON += ", \"Min\": \"Min\""; JSON += ", \"Value\": \"Value\""; JSON += ", \"Max\": \"Max\""; JSON += ", \"ImageURL\": \"\""; JSON += "}"; var responseContent = JSON; byte[] buffer = Encoding.UTF8.GetBytes(responseContent); response.AddHeader("Cache-Control", "no-cache"); response.ContentLength64 = buffer.Length; response.ContentType = "application/json"; try { Stream output = response.OutputStream; output.Write(buffer, 0, buffer.Length); output.Close(); } catch (HttpListenerException) { } response.Close(); }
private void ProcessRequest(HttpListenerRequest request, HttpListenerResponse response) { response.AddHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0"); response.AddHeader("Pragma", "no-cache"); IRequestHandler handler = AssignRequestHandler(request); if (handler != null) { handler.Process(request, response); } else { FinalizeIgnoredResponse(response, 404, "Resource Not Found"); } }
/// <summary> /// /// </summary> /// <param name="response"></param> public HttpListentGameResponse(HttpListenerResponse response) { _response = response; response.ContentType = "application/octet-stream"; response.AddHeader("Access-Control-Allow-Origin", "*"); }
private static async Task CopyFrom(HttpListenerResponse response, HttpResponseMessage message, IReadOnlyDictionary<string, Dictionary<Regex, string>> rules) { response.StatusCode = (int)message.StatusCode; foreach (var httpResponseHeader in message.Headers.Where(header => !ResponseFilter.Contains(header.Key))) { foreach (var value in httpResponseHeader.Value) { response.AddHeader(httpResponseHeader.Key, value); } } foreach ( var httpResponseHeader in message.Content.Headers.Where(header => !ResponseFilter.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 (message.Content.Headers.ContentType != null && rules.ContainsKey(message.Content.Headers.ContentType.MediaType)) { var rule = rules[message.Content.Headers.ContentType.MediaType]; var encoding = GetEncoding(message.Content.Headers.ContentType.CharSet); var content = encoding.GetString(bytes); content = Replace(content, rule); bytes = encoding.GetBytes(content); } response.ContentLength64 = bytes.Length; await response.OutputStream.WriteAsync(bytes, 0, bytes.Length); }
public byte[] GetHTML500(HttpListenerResponse response) { try { // I know this statuscode is dumb, but the client doesn't respond to 404s and 500s response.StatusCode = (int)HttpStatusCode.OK; response.AddHeader("Content-type", "text/html"); string responseString = GetHTTP500(); byte[] buffer = Encoding.UTF8.GetBytes(responseString); response.ContentEncoding = Encoding.UTF8; return buffer; } catch { } return null; }
static bool ServeFile(string path, HttpListenerResponse httpResponse) { if(!File.Exists(path)) { return false; } // http://stackoverflow.com/a/13386573/4264 using(var fs = File.OpenRead(path)) { httpResponse.StatusCode = (int)HttpStatusCode.OK; httpResponse.ContentLength64 = fs.Length; httpResponse.SendChunked = false; httpResponse.ContentType = GetContentType(Path.GetExtension(path)); if(httpResponse.ContentType == "application/octet-stream") { httpResponse.AddHeader("Content-disposition", "attachment; filename=" + Path.GetFileName(path)); } byte[] buffer = new byte[64 * 1024]; int read; using(BinaryWriter bw = new BinaryWriter(httpResponse.OutputStream)) { while((read = fs.Read(buffer, 0, buffer.Length)) > 0) { bw.Write(buffer, 0, read); bw.Flush(); //seems to have no effect } } } return true; }
/// <summary> /// /// </summary> /// <param name="response"></param> /// <param name="data"></param> /// <param name="offset"></param> /// <param name="count"></param> public void PushSend(HttpListenerResponse response, byte[] data, int offset, int count) { 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(); }
public void Send(HttpListenerResponse listenerResponse) { Headers .Where(r => r.Key != "Content-Type") .ForEach(header => listenerResponse.AddHeader(header.Key, header.Value)); listenerResponse.ContentType = Headers["Content-Type"]; listenerResponse.StatusCode = StatusCode; WriteStream(listenerResponse.OutputStream) .Do(stream => { try { stream.Close(); stream.Dispose(); } catch { } }, error => { try { listenerResponse.StatusCode = 500; listenerResponse.OutputStream.Close(); } catch { } }) .Retry() .Subscribe(); }
void Exception (HttpListenerResponse response, Exception exception) { var id = CreateExceptionId (); exceptions [id] = exception; response.AddHeader (ExceptionHeaderName, id.ToString ()); if (exception == null) return; response.StatusCode = 500; using (var writer = new StreamWriter (response.OutputStream)) { writer.WriteLine (string.Format ("EXCEPTION: {0}", exception)); } response.Close (); }
private static void ConvertNancyResponseToResponse(Response nancyResponse, HttpListenerResponse response) { foreach (var header in nancyResponse.Headers) { response.AddHeader(header.Key, header.Value); } foreach (var nancyCookie in nancyResponse.Cookies) { response.Headers.Add(HttpResponseHeader.SetCookie, nancyCookie.ToString()); } response.ContentType = nancyResponse.ContentType; response.StatusCode = (int)nancyResponse.StatusCode; var output = response.OutputStream; nancyResponse.Contents.Invoke(output); if (nancyResponse.DisposeStream) { output.Dispose(); } }
private void ConvertNancyResponseToResponse(Response nancyResponse, HttpListenerResponse response) { foreach (var header in nancyResponse.Headers) { response.AddHeader(header.Key, header.Value); } foreach (var nancyCookie in nancyResponse.Cookies) { response.Headers.Add(HttpResponseHeader.SetCookie, nancyCookie.ToString()); } if (nancyResponse.ReasonPhrase != null) { response.StatusDescription = nancyResponse.ReasonPhrase; } if (nancyResponse.ContentType != null) { response.ContentType = nancyResponse.ContentType; } response.StatusCode = (int)nancyResponse.StatusCode; if (configuration.AllowChunkedEncoding) { OutputWithDefaultTransferEncoding(nancyResponse, response); } else { OutputWithContentLength(nancyResponse, response); } }
/// <summary> /// Callback when a HTTP request comes in on the port listener and is handed off /// to a thread for processing. This method /// </summary> /// <param name="result">IAsyncResult containing the HTTPListener</param> protected void ListenerCallback(IAsyncResult result) { try { HttpListener listener = (HttpListener)result.AsyncState; HttpListenerContext context = null; if (listener == null) { Console.WriteLine("Listener null so returning..."); return; } try { // The EndGetContext() method, as with all Begin/End asynchronous methods in the .NET Framework, // blocks until there is a request to be processed or some type of data is available. context = listener.EndGetContext(result); } catch (Exception ex) { // You will get an exception when httpListener.Stop() is called // because there will be a thread stopped waiting on the .EndGetContext() // method, and again, that is just the way most Begin/End asynchronous // methods of the .NET Framework work. Console.WriteLine("HttpListener Stopped: {0}", ex.Message); ReleaseAllLatches(); return; } finally { // Once we know we have a request (or exception), we signal the other thread // so that it calls the BeginGetContext() (or possibly exits if we're not // listening any more) method to start handling the next incoming request // while we continue to process this request on a different thread. listenForNextRequest.Set(); } if (context == null) { return; } Console.WriteLine("HTTP START: {0}", DateTime.Now.ToString()); System.Net.HttpListenerRequest request = context.Request; Console.WriteLine("{0}: {1}", PORT, request.RawUrl); if (request.HasEntityBody) { using (System.IO.StreamReader sr = new System.IO.StreamReader(request.InputStream, request.ContentEncoding)) { string requestData = sr.ReadToEnd(); } } bool debug_enabled = true; if (debug_enabled) { Console.WriteLine(" HTTP User-Agent: {0}", request.UserAgent); foreach (String s in request.Headers.AllKeys) { Console.WriteLine(" Header {0,-10} {1}", s, request.Headers[s]); } } // determine if the client is requesting a compressed response string acceptEncoding = request.Headers["Accept-Encoding"]; bool isCompressed = (!string.IsNullOrEmpty(acceptEncoding) && (acceptEncoding.Contains("gzip") || acceptEncoding.Contains("deflate"))); Console.WriteLine("Accept-Encoding: {0} Compressed: {1}", acceptEncoding, isCompressed); // Obtain a response object using (System.Net.HttpListenerResponse response = context.Response) { try { response.ContentType = "application/x-dmap-tagged"; response.AddHeader("DAAP-Server", this.GetApplicationName() + " " + this.Version); this.DispatchRequest(request, response, isCompressed); } catch (DACPSecurityException ex) { Console.WriteLine("DACP Security Error: " + ex.Message); response.StatusCode = (int)HttpStatusCode.Forbidden; response.OutputStream.WriteByte(0); } catch (Exception ex) { Console.WriteLine("DACP Server Error: " + ex.Message); response.StatusCode = DACPResponse.MSTT_NO_CONTENT; response.OutputStream.WriteByte(0); } } } catch (Exception httpEx) { Console.WriteLine("DACP Server Error: " + httpEx.Message, httpEx); } Console.WriteLine("HTTP END: {0}", DateTime.Now.ToString()); }
private void ConvertResponse(Response response, HttpListenerResponse httpResponse) { foreach (var header in response.Headers) { if (!IgnoredHeaders.IsIgnored(header.Key)) { httpResponse.AddHeader(header.Key, header.Value); } } foreach (var cookie in response.Cookies) { httpResponse.Headers.Add(HttpResponseHeader.SetCookie, cookie.ToString()); } if (response.ReasonPhrase != null) { httpResponse.StatusDescription = response.ReasonPhrase; } if (response.ContentType != null) { httpResponse.ContentType = response.ContentType; } httpResponse.StatusCode = (int)response.StatusCode; OutputWithContentLength(response, httpResponse); }
private static void WriteResponse(string aUrl, HttpWebResponse aProxiedResponse, HttpListenerResponse aResponse) { aResponse.StatusCode = (int)aProxiedResponse.StatusCode; aResponse.StatusDescription = aProxiedResponse.StatusDescription; int contentLength = 0; foreach (var key in aProxiedResponse.Headers.AllKeys) { switch (key.ToUpper()) { case "CONTENT-LENGTH": // don't set aResponse.ContentLength64 yet as we may re-write some content below (if we're serving Node.js) contentLength = Convert.ToInt32(aProxiedResponse.Headers.GetValues(key)[0]); break; case "CONTENT-TYPE": case "EXT": case "SERVER": string[] values = aProxiedResponse.Headers.GetValues(key); foreach (string val in values) aResponse.Headers.Add(key, val); break; case "TRANSFER-ENCODING": aResponse.SendChunked = (String.Compare(aProxiedResponse.Headers.GetValues(key)[0], "chunked", true) == 0); break; case "CONNECTION": aResponse.Headers.Add(key, aProxiedResponse.Headers.GetValues(key)[0]); break; default: Logger.InfoFormat("Ignored header in response: {0}", key); break; } } bool useGzip = false; if (!aResponse.SendChunked && contentLength > 512 /* no point in zipping tiny responses */ && aProxiedResponse.ContentType != null && !(aProxiedResponse.ContentType.Contains("image/png") || aProxiedResponse.ContentType.Contains("image/jpeg"))) // no point in wasting time zipping a format that is already compressed useGzip = true; Stream clientRespStream = aResponse.OutputStream; using (Stream respStream = aProxiedResponse.GetResponseStream()) { if (aUrl.EndsWith("/Node.js")) { RewriteNodeJsFile(aResponse, respStream); } else if (!useGzip) { if (contentLength > 0) // response may be chunked aResponse.ContentLength64 = contentLength; respStream.CopyTo(clientRespStream); } else { aResponse.AddHeader("Content-Encoding", "gzip"); MemoryStream zip = new MemoryStream(); using (var zipper = new GZipStream(zip, CompressionMode.Compress, true)) { respStream.CopyTo(zipper); } zip.Seek(0, SeekOrigin.Begin); aResponse.ContentLength64 = zip.Length; //Console.WriteLine("Compressed {0} to {1} bytes", contentLength, zip.Length); zip.CopyTo(clientRespStream); } } clientRespStream.Close(); }