public async Task <IHttpResponse> Invoke(IHttpRequest request, CancellationToken cancellationToken) { request.AddHeader("x-special-name", name); request.AddHeader(x => x.ExpectContinue = true); return(await Next.Invoke(request, cancellationToken).ConfigureAwait(false)); }
/// <exception cref="Apache.Http.HttpException"></exception> /// <exception cref="System.IO.IOException"></exception> public virtual void Process(IHttpRequest request, HttpContext context) { Args.NotNull(request, "HTTP request"); string method = request.GetRequestLine().GetMethod(); if (Sharpen.Runtime.EqualsIgnoreCase(method, "CONNECT")) { request.SetHeader(ProxyConnDirective, HTTP.ConnKeepAlive); return; } HttpClientContext clientContext = ((HttpClientContext)HttpClientContext.Adapt(context )); // Obtain the client connection (required) RouteInfo route = clientContext.GetHttpRoute(); if (route == null) { this.log.Debug("Connection route not set in the context"); return; } if (route.GetHopCount() == 1 || route.IsTunnelled()) { if (!request.ContainsHeader(HTTP.ConnDirective)) { request.AddHeader(HTTP.ConnDirective, HTTP.ConnKeepAlive); } } if (route.GetHopCount() == 2 && !route.IsTunnelled()) { if (!request.ContainsHeader(ProxyConnDirective)) { request.AddHeader(ProxyConnDirective, HTTP.ConnKeepAlive); } } }
/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected virtual void OnHeaderReceived(object sender, HeaderEventArgs e) { if (string.Compare(e.Name, "expect", true) == 0 && e.Value.Contains("100-continue")) { Respond("HTTP/1.0", HttpStatusCode.Continue, "Please continue mate."); } _currentRequest.AddHeader(e.Name, e.Value); }
/// <exception cref="Org.Apache.Http.HttpException"></exception> /// <exception cref="System.IO.IOException"></exception> public virtual void Process(IHttpRequest request, HttpContext context) { Args.NotNull(request, "HTTP request"); if (request is HttpEntityEnclosingRequest) { if (this.overwrite) { request.RemoveHeaders(HTTP.TransferEncoding); request.RemoveHeaders(HTTP.ContentLen); } else { if (request.ContainsHeader(HTTP.TransferEncoding)) { throw new ProtocolException("Transfer-encoding header already present"); } if (request.ContainsHeader(HTTP.ContentLen)) { throw new ProtocolException("Content-Length header already present"); } } ProtocolVersion ver = request.GetRequestLine().GetProtocolVersion(); HttpEntity entity = ((HttpEntityEnclosingRequest)request).GetEntity(); if (entity == null) { request.AddHeader(HTTP.ContentLen, "0"); return; } // Must specify a transfer encoding or a content length if (entity.IsChunked() || entity.GetContentLength() < 0) { if (ver.LessEquals(HttpVersion.Http10)) { throw new ProtocolException("Chunked transfer encoding not allowed for " + ver); } request.AddHeader(HTTP.TransferEncoding, HTTP.ChunkCoding); } else { request.AddHeader(HTTP.ContentLen, System.Convert.ToString(entity.GetContentLength ())); } // Specify a content type if known if (entity.GetContentType() != null && !request.ContainsHeader(HTTP.ContentType)) { request.AddHeader(entity.GetContentType()); } // Specify a content encoding if known if (entity.GetContentEncoding() != null && !request.ContainsHeader(HTTP.ContentEncoding )) { request.AddHeader(entity.GetContentEncoding()); } } }
private void AddCommonHeaders(IHttpRequest httpRequest, string token, string projectId) { if (string.IsNullOrEmpty(projectId)) { throw new ArgumentException("project id is null"); } httpRequest.AddHeader("region", smnConfiguration.RegionName); httpRequest.AddHeader("X-Auth-Token", token); httpRequest.AddHeader("X-Project-Id", projectId); httpRequest.AddHeader("X-Smn-Sdk", smnConfiguration.GetUserAgent()); }
/// <summary> /// Set accept headers /// </summary> /// <param name="serializer"></param> /// <param name="request"></param> /// <returns></returns> public static void SetAcceptHeaders(this ISerializer serializer, IHttpRequest request) { if (request == null) { throw new ArgumentNullException(nameof(request)); } request.AddHeader("Accept", serializer.MimeType); if (serializer.ContentEncoding != null) { request.AddHeader("Accept-Charset", serializer.ContentEncoding.WebName); } }
public void Authenticate(IHttpRequest httpRequest) { var token = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Concat(username, ":", password))); var authorizationHeader = string.Concat("Basic ", token); httpRequest.AddHeader("Authorization", authorizationHeader); }
/// <summary> /// Adds the header /// <code>"Accept-Encoding: gzip,deflate"</code> /// to the request. /// </summary> /// <exception cref="Apache.Http.HttpException"></exception> /// <exception cref="System.IO.IOException"></exception> public virtual void Process(IHttpRequest request, HttpContext context) { if (!request.ContainsHeader("Accept-Encoding")) { request.AddHeader("Accept-Encoding", "gzip,deflate"); } }
private void AddHeaderToRequest(IHttpRequest request, string headerLine) { var headerParts = headerLine.Split(new[] { ':' }, 2); var headerName = headerParts[0].Trim(); var headerValue = headerParts.Length == 2 ? headerParts[1].Trim() : string.Empty; request.AddHeader(headerName, headerValue); }
/// <exception cref="Apache.Http.HttpException"></exception> /// <exception cref="System.IO.IOException"></exception> public virtual void Process(IHttpRequest request, HttpContext context) { Args.NotNull(request, "HTTP request"); string method = request.GetRequestLine().GetMethod(); if (Sharpen.Runtime.EqualsIgnoreCase(method, "CONNECT")) { return; } // Add default headers ICollection <Header> defHeaders = (ICollection <Header>)request.GetParams().GetParameter (ClientPNames.DefaultHeaders); if (defHeaders == null) { defHeaders = this.defaultHeaders; } if (defHeaders != null) { foreach (Header defHeader in defHeaders) { request.AddHeader(defHeader); } } }
private void AddHeaderToRequest(IHttpRequest request, string headerLine) { string[] headerParts = headerLine.Split(new[] { ':' }, 2); string headerName = headerParts[0].Trim(); string headerValue = headerParts.Length == 2 ? headerParts[1].Trim() : string.Empty; request.AddHeader(headerName, headerValue); }
/// <exception cref="Org.Apache.Http.HttpException"></exception> /// <exception cref="System.IO.IOException"></exception> public virtual void Process(IHttpRequest request, HttpContext context) { Args.NotNull(request, "HTTP request"); string method = request.GetRequestLine().GetMethod(); if (Sharpen.Runtime.EqualsIgnoreCase(method, "CONNECT")) { return; } if (!request.ContainsHeader(HTTP.ConnDirective)) { // Default policy is to keep connection alive // whenever possible request.AddHeader(HTTP.ConnDirective, HTTP.ConnKeepAlive); } }
/// <exception cref="Org.Apache.Http.HttpException"></exception> /// <exception cref="System.IO.IOException"></exception> public virtual void Process(IHttpRequest request, HttpContext context) { Args.NotNull(request, "HTTP request"); HttpCoreContext corecontext = HttpCoreContext.Adapt(context); ProtocolVersion ver = request.GetRequestLine().GetProtocolVersion(); string method = request.GetRequestLine().GetMethod(); if (Sharpen.Runtime.EqualsIgnoreCase(method, "CONNECT") && ver.LessEquals(HttpVersion .Http10)) { return; } if (!request.ContainsHeader(HTTP.TargetHost)) { HttpHost targethost = corecontext.GetTargetHost(); if (targethost == null) { HttpConnection conn = corecontext.GetConnection(); if (conn is HttpInetConnection) { // Populate the context with a default HTTP host based on the // inet address of the target host IPAddress address = ((HttpInetConnection)conn).GetRemoteAddress(); int port = ((HttpInetConnection)conn).GetRemotePort(); if (address != null) { targethost = new HttpHost(address.GetHostName(), port); } } if (targethost == null) { if (ver.LessEquals(HttpVersion.Http10)) { return; } else { throw new ProtocolException("Target host missing"); } } } request.AddHeader(HTTP.TargetHost, targethost.ToHostString()); } }
public async Task TestGetRequestWithHeader() { SystemNetHttpServiceModule module = new SystemNetHttpServiceModule(); IHttpRequest request = module.NewRequest(); IHttpResponse response = await request .AddHeader(TEST_HEADER, TEST_HEADER1_VALUE) .AddHeader(TEST_HEADER, TEST_HEADER2_VALUE).Get(localPath(GET_TEST_WITH_HEADER_PATH)).Execute(); Assert.NotNull(response); Assert.Null(response.Error); Assert.IsTrue(response.Successful); Assert.AreEqual(200, response.StatusCode); var jsonObject = JsonObject.Parse(response.Body); Assert.AreEqual(HELLO_WORLD, (string)jsonObject["text"]); Assert.AreEqual($"{TEST_HEADER1_VALUE}, {TEST_HEADER2_VALUE}", (string)jsonObject["headerValues"], "header check"); }
/// <exception cref="Org.Apache.Http.HttpException"></exception> /// <exception cref="System.IO.IOException"></exception> public virtual void Process(IHttpRequest request, HttpContext context) { Args.NotNull(request, "HTTP request"); if (!request.ContainsHeader(HTTP.UserAgent)) { string s = null; HttpParams @params = request.GetParams(); if (@params != null) { s = (string)@params.GetParameter(CoreProtocolPNames.UserAgent); } if (s == null) { s = this.userAgent; } if (s != null) { request.AddHeader(HTTP.UserAgent, s); } } }
/// <exception cref="Org.Apache.Http.HttpException"></exception> /// <exception cref="System.IO.IOException"></exception> public virtual void Process(IHttpRequest request, HttpContext context) { Args.NotNull(request, "HTTP request"); if (!request.ContainsHeader(HTTP.ExpectDirective)) { if (request is HttpEntityEnclosingRequest) { ProtocolVersion ver = request.GetRequestLine().GetProtocolVersion(); HttpEntity entity = ((HttpEntityEnclosingRequest)request).GetEntity(); // Do not send the expect header if request body is known to be empty if (entity != null && entity.GetContentLength() != 0 && !ver.LessEquals(HttpVersion .Http10)) { bool active = request.GetParams().GetBooleanParameter(CoreProtocolPNames.UseExpectContinue , this.activeByDefault); if (active) { request.AddHeader(HTTP.ExpectDirective, HTTP.ExpectContinue); } } } } }
/// <exception cref="Apache.Http.HttpException"></exception> /// <exception cref="System.IO.IOException"></exception> public virtual void Process(IHttpRequest request, HttpContext context) { Args.NotNull(request, "HTTP request"); if (!request.ContainsHeader(HTTP.ExpectDirective)) { if (request is HttpEntityEnclosingRequest) { ProtocolVersion ver = request.GetRequestLine().GetProtocolVersion(); HttpEntity entity = ((HttpEntityEnclosingRequest)request).GetEntity(); // Do not send the expect header if request body is known to be empty if (entity != null && entity.GetContentLength() != 0 && !ver.LessEquals(HttpVersion .Http10)) { HttpClientContext clientContext = ((HttpClientContext)HttpClientContext.Adapt(context )); RequestConfig config = clientContext.GetRequestConfig(); if (config.IsExpectContinueEnabled()) { request.AddHeader(HTTP.ExpectDirective, HTTP.ExpectContinue); } } } } }
public async Task <IHttpResponse> Invoke(IHttpRequest request, CancellationToken cancellationToken) { request.AddHeader(x => x.UserAgent.ParseAdd(UserAgent.Name)); return(await Next.Invoke(request, cancellationToken).ConfigureAwait(false)); }
/// <exception cref="Apache.Http.HttpException"></exception> /// <exception cref="System.IO.IOException"></exception> public virtual void Process(IHttpRequest request, HttpContext context) { Args.NotNull(request, "HTTP request"); Args.NotNull(context, "HTTP context"); string method = request.GetRequestLine().GetMethod(); if (Sharpen.Runtime.EqualsIgnoreCase(method, "CONNECT")) { return; } HttpClientContext clientContext = ((HttpClientContext)HttpClientContext.Adapt(context )); // Obtain cookie store CookieStore cookieStore = clientContext.GetCookieStore(); if (cookieStore == null) { this.log.Debug("Cookie store not specified in HTTP context"); return; } // Obtain the registry of cookie specs Lookup <CookieSpecProvider> registry = clientContext.GetCookieSpecRegistry(); if (registry == null) { this.log.Debug("CookieSpec registry not specified in HTTP context"); return; } // Obtain the target host, possibly virtual (required) HttpHost targetHost = clientContext.GetTargetHost(); if (targetHost == null) { this.log.Debug("Target host not set in the context"); return; } // Obtain the route (required) RouteInfo route = clientContext.GetHttpRoute(); if (route == null) { this.log.Debug("Connection route not set in the context"); return; } RequestConfig config = clientContext.GetRequestConfig(); string policy = config.GetCookieSpec(); if (policy == null) { policy = CookieSpecs.BestMatch; } if (this.log.IsDebugEnabled()) { this.log.Debug("CookieSpec selected: " + policy); } URI requestURI = null; if (request is IHttpUriRequest) { requestURI = ((IHttpUriRequest)request).GetURI(); } else { try { requestURI = new URI(request.GetRequestLine().GetUri()); } catch (URISyntaxException) { } } string path = requestURI != null?requestURI.GetPath() : null; string hostName = targetHost.GetHostName(); int port = targetHost.GetPort(); if (port < 0) { port = route.GetTargetHost().GetPort(); } CookieOrigin cookieOrigin = new CookieOrigin(hostName, port >= 0 ? port : 0, !TextUtils .IsEmpty(path) ? path : "/", route.IsSecure()); // Get an instance of the selected cookie policy CookieSpecProvider provider = registry.Lookup(policy); if (provider == null) { throw new HttpException("Unsupported cookie policy: " + policy); } CookieSpec cookieSpec = provider.Create(clientContext); // Get all cookies available in the HTTP state IList <Apache.Http.Cookie.Cookie> cookies = new AList <Apache.Http.Cookie.Cookie>(cookieStore .GetCookies()); // Find cookies matching the given origin IList <Apache.Http.Cookie.Cookie> matchedCookies = new AList <Apache.Http.Cookie.Cookie >(); DateTime now = new DateTime(); foreach (Apache.Http.Cookie.Cookie cookie in cookies) { if (!cookie.IsExpired(now)) { if (cookieSpec.Match(cookie, cookieOrigin)) { if (this.log.IsDebugEnabled()) { this.log.Debug("Cookie " + cookie + " match " + cookieOrigin); } matchedCookies.AddItem(cookie); } } else { if (this.log.IsDebugEnabled()) { this.log.Debug("Cookie " + cookie + " expired"); } } } // Generate Cookie request headers if (!matchedCookies.IsEmpty()) { IList <Header> headers = cookieSpec.FormatCookies(matchedCookies); foreach (Header header in headers) { request.AddHeader(header); } } int ver = cookieSpec.GetVersion(); if (ver > 0) { bool needVersionHeader = false; foreach (Apache.Http.Cookie.Cookie cookie_1 in matchedCookies) { if (ver != cookie_1.GetVersion() || !(cookie_1 is SetCookie2)) { needVersionHeader = true; } } if (needVersionHeader) { Header header = cookieSpec.GetVersionHeader(); if (header != null) { // Advertise cookie version support request.AddHeader(header); } } } // Stick the CookieSpec and CookieOrigin instances to the HTTP context // so they could be obtained by the response interceptor context.SetAttribute(HttpClientContext.CookieSpec, cookieSpec); context.SetAttribute(HttpClientContext.CookieOrigin, cookieOrigin); }
/// <exception cref="Apache.Http.HttpException"></exception> /// <exception cref="System.IO.IOException"></exception> public virtual void GenerateAuthResponse(IHttpRequest request, AuthState authState , HttpContext context) { AuthScheme authScheme = authState.GetAuthScheme(); Credentials creds = authState.GetCredentials(); switch (authState.GetState()) { case AuthProtocolState.Failure: { return; } case AuthProtocolState.Success: { EnsureAuthScheme(authScheme); if (authScheme.IsConnectionBased()) { return; } break; } case AuthProtocolState.Challenged: { Queue <AuthOption> authOptions = authState.GetAuthOptions(); if (authOptions != null) { while (!authOptions.IsEmpty()) { AuthOption authOption = authOptions.Remove(); authScheme = authOption.GetAuthScheme(); creds = authOption.GetCredentials(); authState.Update(authScheme, creds); if (this.log.IsDebugEnabled()) { this.log.Debug("Generating response to an authentication challenge using " + authScheme .GetSchemeName() + " scheme"); } try { Header header = DoAuth(authScheme, creds, request, context); request.AddHeader(header); break; } catch (AuthenticationException ex) { if (this.log.IsWarnEnabled()) { this.log.Warn(authScheme + " authentication error: " + ex.Message); } } } return; } else { EnsureAuthScheme(authScheme); } } } if (authScheme != null) { try { Header header = DoAuth(authScheme, creds, request, context); request.AddHeader(header); } catch (AuthenticationException ex) { if (this.log.IsErrorEnabled()) { this.log.Error(authScheme + " authentication error: " + ex.Message); } } } }
public static IHttpRequest RandomXFowardFor(this IHttpRequest request) { request.AddHeader("X-Forwarded-For", GetRandomIpAddress()); return(request); }