public void RemoveConnection(HttpConnection connection) { lock (this._requests) { this._requests.Remove(connection); } }
internal HttpListenerContext (HttpConnection cnc) { this.cnc = cnc; err_status = 400; request = new HttpListenerRequest (this); response = new HttpListenerResponse (this); }
IObservable<HttpConnection> GetConnection(Uri uri) { if(m_connection!= null && m_connection.Uri.Host==uri.Host && m_connection.Uri.Port==uri.Port && m_connection.IsConnected ) { return Observable.Return(m_connection) .Do(x => { Console.WriteLine("<KeepAlive>"); }) ; } else { return HttpConnection.Create(uri).Connect() .Do(x => { m_connection = x; Console.WriteLine(x); }) ; } }
public void Setup() { requestedUrl.Clear(); partialData = false; int i; for (i = 0; i < 1000; i++) { try { listener = new HttpListener(); listener.Prefixes.Add(string.Format(listenerURL, i)); listener.Start(); break; } catch { } } listener.BeginGetContext(GotContext, null); rig = TestRig.CreateMultiFile(); connection = new HttpConnection(new Uri(string.Format(listenerURL, i))); connection.Manager = rig.Manager; id = new PeerId(new Peer("this is my id", connection.Uri), rig.Manager); id.Connection = connection; id.IsChoking = false; id.AmInterested = true; id.BitField.SetAll(true); id.MaxPendingRequests = numberOfPieces; requests = rig.Manager.PieceManager.Picker.PickPiece(id, new List<PeerId>(), numberOfPieces); }
internal HttpListenerContext(HttpConnection cnc, ILogger logger) { this.cnc = cnc; _logger = logger; request = new HttpListenerRequest(this); response = new HttpListenerResponse(this, _logger); }
public void SendMessageSendsAndReceivesAMessage() { var action = "DoSomething"; var request = new ServerRequest { ServerName = "TestServer" }; var url = "http://somewhere/"; var factory = new TestClientFactory((u, a, d) => { Assert.AreEqual(url + "server/TestServer/RawXmlMessage.aspx", u.AbsoluteUri); Assert.AreEqual("POST", a); Assert.AreEqual(action, d["action"]); Assert.AreEqual(request.ToString(), d["message"]); var theResponse = new Response { RequestIdentifier = request.Identifier }; return Encoding.UTF8.GetBytes(theResponse.ToString()); }); var connection = new HttpConnection(new Uri(url), factory); var response = connection.SendMessage(action, request); Assert.IsInstanceOf<Response>(response); Assert.AreEqual(request.Identifier, response.RequestIdentifier); }
protected ApiClient(ApiKeyConnection connection) { Ensure.ArgumentNotNull(connection, nameof(connection)); ApiKeyConnection = connection; HttpConnection = new HttpConnection(ApiKeyConnection); }
public void ExecuteTest() { HttpConnection target = new HttpConnection(); HttpWebRequest httpRequest = GetHttpWebRequest(); string actual = target.Execute(payLoad, httpRequest); Assert.IsNotNull(actual); }
void Close() { if(m_connection!=null && m_connection.IsConnected) { (m_connection as IDisposable).Dispose(); m_connection = null; } }
public Client(HttpConnection connection) { _nodeName = Environment.GetEnvironmentVariable("CONSUL_CLIENT_NODE_NAME") ?? "undefined node"; _serviceName = Environment.GetEnvironmentVariable("CONSUL_CLIENT_SERVICE_NAME") ?? "undefined service"; _datacenterName = Environment.GetEnvironmentVariable("CONSUL_CLIENT_DATACENTER_NAME") ?? "dc1"; _catalog = new Catalog(connection); }
// private bool _headersSent; /// <summary> /// Initializes a new instance of the AspWorkerRequest class /// </summary> /// <param name="connection"></param> /// <param name="request"></param> public AspWorkerRequest(AspHost aspHost, HttpConnection connection, HttpRequest request) : base(string.Empty, string.Empty, null) { _aspHost = aspHost; _connection = connection; _request = request; _response = new HttpResponse(new OkStatus()); this.ParsePathInfo(); }
public void Dispose() { lock (this) { if (_httpConnection != null) { _httpConnection.Dispose(); _httpConnection = null; } } }
/// <summary> /// Initializes a new instance of the AddressBookItemConnectionManager class /// </summary> /// <param name="item">The address book item that defines the remote host to connect to</param> /// <param name="connection">The Tcp connection that will be used throughout the lifetime of the connection</param> public AddressBookItemConnectionManager(AddressBookItem item, HttpConnection connection) { if (item == null) throw new ArgumentNullException("item"); if (connection == null) throw new ArgumentNullException("connection"); _propertyBag = new Hashtable(); _item = item; _connection = connection; _connection.Opened += new HttpConnectionEventHandler(OnInternalConnectionOpened); _connection.Closed += new HttpConnectionEventHandler(OnInternalConnectionClosed); _connection.Exception += new ExceptionEventHandler(OnInternalConnectionException); }
public NanoHttpRequest(HttpConnection conn, string request) { Connection = conn; if (string.IsNullOrEmpty(request)) { Invalid = true; return; } var fls = request.Split(new char[]{ ' ' }, 3); if (fls.Length < 2) { Invalid = true; return; } Method = fls[0]; Address = fls[1]; //if (Method == "POST") { var heco = request.Split(new string[]{ "\r\n\r\n" }, 2, StringSplitOptions.None); if (heco.Length < 2) { Invalid = true; return; } var he = heco[0]; var co = heco[1]; Content = co; var lines = he.Split(new string[]{ "\r\n", "\n" }, StringSplitOptions.None); for (int i = 1; i < lines.Length; i++) { var hl = lines[i].Split(new String[]{": "}, 2, StringSplitOptions.None); if (hl.Length < 2) continue; Headers[hl[0]] = hl[1]; } } }
public void RequestTimeout(HttpConnection connection) { var param = connection.Param; int msgId = param.Get("MsgId").ToInt(); int actionId = param.Get("ActionId").ToInt(); int errorCode = LanguageHelper.GetLang().ErrorCode; string errorMsg = LanguageHelper.GetLang().RequestTimeout; var head = new MessageHead(msgId, actionId, "st", errorCode, errorMsg); head.HasGzip = true; var ms = new MessageStructure(); ms.WriteBuffer(head); byte[] data = ms.ReadBuffer(); string remoteAddress = connection.Context.Request.RemoteEndPoint.Address.ToString(); string successMsg = string.Format("{0}>>发送超时到{1} {2}字节!", DateTime.Now.ToString("HH:mm:ss:ms"), remoteAddress, data.Length); Console.WriteLine(successMsg); OnResponseCompleted(connection, data); }
private void Process(HttpConnection connection, NanoHttpRequest request) { if (request.Address == "/") { connection.Response(_root.Handle(request)); return; } var endpoint = request.Address.Split(new char[]{'/'}, StringSplitOptions.RemoveEmptyEntries)[0]; if (_handlers.ContainsKey(endpoint)) { connection.Response(_handlers[endpoint].Handle(request)); } else { connection.Response(new ErrorHandler(StatusCode.BadRequest, "Unknown endpoint: " + endpoint).Handle(request)); } }
protected override void Run() { this._listener.Start(); while (true) { try { TcpClient client = this._listener.AcceptTcpClient(); HttpConnection connection = new HttpConnection(this, client); lock (this._requests) { this._requests.Add(connection); } connection.Start(); } catch { } } }
public virtual void OnAccept( IAsyncResult ar ) { try { Socket newSocket = listenSocket.EndAccept( ar ); if ( newSocket != null ) { HttpConnection newClient = new HttpConnection( newSocket, new RemoveClientDelegate( this.RemoveClient ) ); clients.Add( newClient ); newClient.Start(); } } catch {} try { listenSocket.BeginAccept( new AsyncCallback( this.OnAccept ), listenSocket ); } catch { Dispose(); } }
internal HttpRequest(IPEndPoint client, string method, string path, string protocol, string version, NameValueCollection headers, byte[] postData, HttpConnection connection) { m_connection = connection; Client = client; Method = method; var pathDelim = path.IndexOf('?'); if (pathDelim == -1) { Path = HttpUtility.UrlDecode(path); QueryString = new NameValueCollection(); } else { Path = HttpUtility.UrlDecode(path.Substring(0, pathDelim)); QueryString = HttpUtility.ParseQueryString(path.Substring(pathDelim + 1)); } Protocol = protocol; Version = version; Headers = headers; PostData = postData; }
public void Request(HttpConnection connection, string clientAddress, byte[] data) { string paramString = string.Empty; try { paramString = Encoding.ASCII.GetString(data); PacketMessage packet = ParsePacketMessage(clientAddress, paramString, ConnectType.Http); packet.Head.SSID = connection.SSID.ToString("N"); HttpConnectionManager.Push(connection); if (ReceiveCompleted != null) { //分发送到游戏服 byte[] packData = packet.ToByte(); string successMsg = string.Format("{0}>>{1}接收到{2}字节!", DateTime.Now.ToString("HH:mm:ss:ms"), clientAddress, data.Length); ReceiveCompleted.BeginInvoke(clientAddress, packData, OnReceiveCompleted, successMsg); } } catch (Exception ex) { TraceLog.WriteError("Receive form http request:{0} error:{1}", paramString, ex); } }
public async Task ConnectionCanSendAndReceiveMessages(TransportType transportType, TransferMode requestedTransferMode) { using (StartLog(out var loggerFactory, testName: $"ConnectionCanSendAndReceiveMessages_{transportType.ToString()}")) { var logger = loggerFactory.CreateLogger <EndToEndTests>(); const string message = "Major Key"; var url = _serverFixture.Url + "/echo"; var connection = new HttpConnection(new Uri(url), transportType, loggerFactory); connection.Features.Set <ITransferModeFeature>( new TransferModeFeature { TransferMode = requestedTransferMode }); try { var receiveTcs = new TaskCompletionSource <string>(); connection.OnReceived((data, state) => { logger.LogInformation("Received {length} byte message", data.Length); if (IsBase64Encoded(requestedTransferMode, connection)) { data = Convert.FromBase64String(Encoding.UTF8.GetString(data)); } var tcs = (TaskCompletionSource <string>)state; tcs.TrySetResult(Encoding.UTF8.GetString(data)); return(Task.CompletedTask); }, receiveTcs); logger.LogInformation("Starting connection to {url}", url); await connection.StartAsync().OrTimeout(); logger.LogInformation("Started connection to {url}", url); var bytes = Encoding.UTF8.GetBytes(message); // Need to encode binary payloads sent over text transports if (IsBase64Encoded(requestedTransferMode, connection)) { bytes = Encoding.UTF8.GetBytes(Convert.ToBase64String(bytes)); } logger.LogInformation("Sending {length} byte message", bytes.Length); try { await connection.SendAsync(bytes).OrTimeout(); } catch (OperationCanceledException) { // Because the server and client are run in the same process there is a race where websocket.SendAsync // can send a message but before returning be suspended allowing the server to run the EchoEndpoint and // send a close frame which triggers a cancellation token on the client and cancels the websocket.SendAsync. // Our solution to this is to just catch OperationCanceledException from the sent message if the race happens // because we know the send went through, and its safe to check the response. } logger.LogInformation("Sent message", bytes.Length); logger.LogInformation("Receiving message"); Assert.Equal(message, await receiveTcs.Task.OrTimeout()); logger.LogInformation("Completed receive"); await connection.Closed.OrTimeout(); } catch (Exception ex) { logger.LogInformation(ex, "Test threw exception"); throw; } finally { logger.LogInformation("Disposing Connection"); await connection.DisposeAsync().OrTimeout(); logger.LogInformation("Disposed Connection"); } } }
public ChunkedEncodingWriteStream(HttpConnection connection) : base(connection) { }
private string GenerateOAuthToken(string base64ClientID) { string response = null; Uri uniformResourceIdentifier = null; Uri baseUri = null; if (config.ContainsKey(BaseConstants.OAUTH_ENDPOINT)) { baseUri = new Uri(config[BaseConstants.OAUTH_ENDPOINT]); } else if (config.ContainsKey(BaseConstants.END_POINT_CONFIG)) { baseUri = new Uri(config[BaseConstants.END_POINT_CONFIG]); } bool success = Uri.TryCreate(baseUri, OAUTHTOKENPATH, out uniformResourceIdentifier); ConnectionManager connManager = ConnectionManager.Instance; HttpWebRequest httpRequest = connManager.GetConnection(ConfigManager.Instance.GetProperties(), uniformResourceIdentifier.AbsoluteUri); Dictionary<string, string> headers = new Dictionary<string, string>(); headers.Add("Authorization", "Basic " + base64ClientID); string postRequest = "grant_type=client_credentials"; httpRequest.Method = "POST"; httpRequest.Accept = "*/*"; httpRequest.UserAgent = RESTConfiguration.FormUserAgentHeader(); foreach (KeyValuePair<string, string> header in headers) { httpRequest.Headers.Add(header.Key, header.Value); } HttpConnection httpConnection = new HttpConnection(config); response = httpConnection.Execute(postRequest, httpRequest); JObject deserializedObject = (JObject)JsonConvert.DeserializeObject(response); string generatedToken = (string)deserializedObject["token_type"] + " " + (string)deserializedObject["access_token"]; appID = (string)deserializedObject["app_id"]; secondsToExpire = (int)deserializedObject["expires_in"]; timeInMilliseconds = DateTime.Now.Millisecond; return generatedToken; }
private void _RequestLineRecieved(string[] words) { _idleTimer.Dispose(); _idleTimer = new Timer(new TimerCallback(_IdleTimeout), null, _CONNECTION_IDLE_TIMEOUT, Timeout.Infinite); _currentConnection = this; if (words[0].ToUpper() != "HTTP"&&!_shutdown) { HttpRequest req = Requests.Dequeue(); lock (_requests) { req.StartRequest(_rand.NextLong(), words, this, ref _parser); _requests.Add(req); } } }
public HttpContentWriteStream(HttpConnection connection) { Debug.Assert(connection != null); _connection = connection; }
public async Task <AnalyticsListResponse <EventAnalytic> > GetEventAnalyticsListAsync() { return(await HttpConnection.GetAsync <AnalyticsListResponse <EventAnalytic> >("/analytics/events/list")); }
public AccessTokenHttpMessageHandler(HttpMessageHandler inner, HttpConnection httpConnection) : base(inner) { _httpConnection = httpConnection; }
private HttpResponse Navigate(HttpRequest request, HttpBehavior httpBehavior) { bool ContinueRedirect = true; HttpResponse response = null; HttpConnectionFactory connFactory = new HttpConnectionFactory(); HttpConnection connection = connFactory.GetConnnection(request.Uri, this.m_proxy); HttpBehavior.RedirectStep rs = null; string redirectUri = null; int responseCode = 0; int redirectCounter = 0; try { while (ContinueRedirect) { try { response = SendRequestAndGetResponse(connection, request); redirectUri = response.Location; responseCode = response.ResponseCode; // response code 100 means that we need to wait for another response // and receive the response from the socket again on the same connection if (responseCode == 100) { response = GetResponse(connection); redirectUri = response.Location; responseCode = response.ResponseCode; } if (httpBehavior != null) { rs = httpBehavior.GetNextStep(); rs.Compare(responseCode, redirectUri); ContinueRedirect = !httpBehavior.IsEmpty(); } else { ContinueRedirect = (redirectCounter < this.m_maxRedirects && (responseCode == 301 || responseCode == 302)); redirectCounter++; } if (ContinueRedirect) { request = new HttpGet(new Uri(redirectUri)); // make sure the connection is still open and redirect url is from the same host connection = connFactory.GetConnnection(request.Uri, this.m_proxy, connection); } } catch (Exception ex) { int i = 0; throw ex; } } } finally { connection.Close(); } return(response); }
/// <summary> /// Runs the background thread that listens for incoming connections /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnThreadRun(object sender, BackgroundThreadStartEventArgs e) { try { IPEndPoint ep = (IPEndPoint)e.Args[0]; Debug.Assert(ep != null); Trace.WriteLineIf(_verbose, string.Format("Binding to the end point '{0}'.", ep.ToString()), TraceCategory); _listeningSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _listeningSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1); _listeningSocket.Bind(ep); Trace.WriteLineIf(_verbose, string.Format("Listening for inbound connections on '{0}'.", ep.ToString()), TraceCategory); while(true) { _listeningSocket.Listen(100); // pending connections queue length // accept the connection Socket socket = _listeningSocket.Accept(); Trace.WriteLineIf(_verbose, string.Format("Accepted an inbound connection from '{0}'.", socket.RemoteEndPoint.ToString()), TraceCategory); // create a new connection for the connection HttpConnection connection = new HttpConnection(socket, _verbose); connection.RequestDispatcher = _dispatcher; connection.Exception += new EventHandler<ExceptionEventArgs>(this.OnConnectionException); connection.Opened += new EventHandler<HttpConnectionEventArgs>(this.OnConnectionOpened); connection.Closed += new EventHandler<HttpConnectionEventArgs>(this.OnConnectionClosed); connection.IsServerSideConnection = true; connection.BeginSession(true); } } catch(ThreadAbortException) { } catch(Exception ex) { this.OnException(this, new ExceptionEventArgs(ex)); } }
public ChunkedEncodingReadStream(HttpConnection connection) : base(connection) { _chunkBytesRemaining = 0; }
public void IsBusyReturnsFalseWhenNothingIsHappening() { var connection = new HttpConnection("http://somewhere"); Assert.IsFalse(connection.IsBusy); }
internal static WsStream CreateServerStream(HttpListenerContext context) { HttpConnection connection = context.Connection; return(new WsStream(connection.Stream, connection.IsSecure)); }
public ContentLengthWriteStream(HttpConnection connection) : base(connection) { }
public void TestConnectionInitialize() { var connection = new HttpConnection(ElasticUrl); Assert.IsNotNull(connection); }
/// <summary> /// Connects to the server specified by the endpoint, sends the request and waits for a response. /// </summary> /// <param name="ep">The address:port of the server</param> /// <param name="request">The request to send</param> /// <param name="exception">Any exception that is throw or encountered during the request/response session with the server</param> /// <param name="verbose">A flag that indicates the connection's verbosity level, true for more messages</param> /// <returns></returns> public static HttpResponse GetResponse( IPEndPoint ep, HttpRequest request, out Exception exception, bool verbose, EventHandler<HttpMessageProgressEventArgs> onSendProgress, EventHandler<HttpMessageProgressEventArgs> onRecvProgress, object stateObject) { #region Params Validation if (ep == null) throw new ArgumentNullException("ep"); if (request == null) throw new ArgumentNullException("request"); exception = null; #endregion // define a connection for this request/response session HttpConnection connection = null; try { // create a connection to the remote end point connection = new HttpConnection(ep, false, verbose, HttpOptions.SendTimeout, HttpOptions.RecvTimeout); // return a response from the server return HttpRequest.GetResponse(connection, request, out exception, onSendProgress, onRecvProgress, stateObject); } catch (ThreadAbortException) { } catch(Exception ex) { //Debug.WriteLine(ex); exception = ex; } finally { // always try and close the connect up afterwards if (connection != null) connection.Close(); } return null; }
private void WalkCallback(HttpConnection connection) { connection.Tick(_now); }
internal void RemoveConnection (HttpConnection connection) { lock (_unregisteredSync) _unregistered.Remove (connection); }
private void OnReceive(IAsyncResult ar) { _currentConnection = this; if (_idleTimer != null) { try { _idleTimer.Change(_CONNECTION_IDLE_TIMEOUT, Timeout.Infinite); } catch (Exception e) { } } // been closed by our side. if (_inputStream == null) return; try { int bytesLeft = _inputStream.EndRead(ar); if (bytesLeft == 0) { Logger.Trace("Client disconnected."); if (_requests.Count > 0) { throw new ParserException("Failed to send complete request"); } else { Close(); return; } } Logger.Debug(Client.ToString() + " received " + bytesLeft + " bytes."); if (bytesLeft < 5000) { string temp = Encoding.Default.GetString(_buffer, 0, bytesLeft); Logger.Trace(temp); } int offset = _parser.Parse(_buffer,0,bytesLeft); bytesLeft -= offset; if (bytesLeft > 0) { Logger.Trace("Moving " + bytesLeft + " from " + offset + " to beginning of array."); Buffer.BlockCopy(_buffer, offset, _buffer, 0, bytesLeft); } try { _inputStream.BeginRead(_buffer, 0, _buffer.Length - offset, OnReceive, null); } catch (Exception e) { Close(); } } catch (ParserException err) { Logger.Trace(err.ToString()); SendBuffer(Encoding.Default.GetBytes("HTTP/1.0 " + ((int)HttpStatusCode.BadRequest).ToString() + " " + err.Message),false); Close(); } catch (Exception err) { if (!(err is IOException)) { Logger.Error("Failed to read from stream: " + err); SendBuffer(Encoding.Default.GetBytes("HTTP/1.0 " + ((int)HttpStatusCode.InternalServerError).ToString() + " " + err.Message),false); } Close(); } }
/// <summary> /// Creates a new IConnection to a URL. Use to fetch and parse a HTML page. /// Use examples: /// <ul> /// <li><code>Document doc = NSoupClient.Connect("http://example.com").UserAgent("Mozilla").Data("name", "jsoup").Get();</code></li> /// <li><code>Document doc = NSoupClient.Connect("http://example.com").Cookie("auth", "token").Post();</code></li> /// </ul> /// </summary> /// <param name="url">URL to connect to. The protocol must be <code>http</code> or <code>https</code>.</param> /// <returns>the connection. You can add data, cookies, and headers; set the user-agent, referrer, method; and then execute.</returns> public static IConnection Connect(string url) { return(HttpConnection.Connect(url)); }
internal static void SetCurrentConnection(HttpConnection con) { _currentConnection = con; }
public HttpContentStream(HttpConnection connection) { _connection = connection; }
/// <summary> /// Sends the specified request and waits for a response using the specified connection. /// </summary> /// <param name="connection">The connection to use for communication</param> /// <param name="request">The request to send</param> /// <param name="exception">Any exception that is throw or encountered during the request/response session with the server</param> /// <returns></returns> public static HttpResponse GetResponse( HttpConnection connection, HttpRequest request, out Exception exception, EventHandler<HttpMessageProgressEventArgs> onSendProgress, EventHandler<HttpMessageProgressEventArgs> onRecvProgress, object stateObject) { #region Params Validation if (connection == null) throw new ArgumentNullException("connection"); if (request == null) throw new ArgumentNullException("request"); exception = null; #endregion // use the connection to get a response HttpResponse response = connection.GetResponse(request, onSendProgress, onRecvProgress, stateObject); exception = connection.GetLastException(); // if there is no response, then obviously something went wrong, retrieve the last exception from the connection if (response == null) { if (exception != null) if (exception.GetType() == typeof(ThreadAbortException)) throw exception; } // return the response return response; }
public ConnectionCloseReadStream(HttpConnection connection) : base(connection) { }
private static void processAccepted (Socket socket, EndPointListener listener) { HttpConnection conn = null; try { conn = new HttpConnection (socket, listener); lock (listener._unregisteredSync) listener._unregistered[conn] = conn; conn.BeginReadRequest (); } catch { if (conn != null) { conn.Close (true); return; } socket.Close (); } }
protected internal override HttpResponse HandleRequest(TestContext ctx, HttpConnection connection, HttpRequest request, RequestFlags effectiveFlags) { Debug(ctx, 2, "HANDLE POST", request.Path, request.Method, effectiveFlags); if (request.Headers.ContainsKey("X-Mono-Redirected")) { effectiveFlags |= RequestFlags.Redirected; } if ((effectiveFlags & RequestFlags.RedirectedAsGet) != 0) { if (!ctx.Expect(request.Method, Is.EqualTo("GET"), "method")) { return(null); } } else if (Method != null) { if (!ctx.Expect(request.Method, Is.EqualTo(Method), "method")) { return(null); } } else { if (!ctx.Expect(request.Method, Is.EqualTo("POST").Or.EqualTo("PUT"), "method")) { return(null); } } if (customHandler != null) { var customResponse = customHandler(request); if (customResponse != null) { return(customResponse); } } var hasContentLength = request.Headers.ContainsKey("Content-Length"); var hasTransferEncoding = request.Headers.ContainsKey("Transfer-Encoding"); if ((effectiveFlags & RequestFlags.RedirectedAsGet) != 0) { ctx.Expect(hasContentLength, Is.False, "Content-Length header not allowed"); ctx.Expect(hasTransferEncoding, Is.False, "Transfer-Encoding header not allowed"); return(HttpResponse.CreateSuccess()); } if ((effectiveFlags & RequestFlags.NoContentLength) != 0) { ctx.Expect(hasContentLength, Is.False, "Content-Length header not allowed"); ctx.Expect(hasTransferEncoding, Is.False, "Transfer-Encoding header not allowed"); } Debug(ctx, 2, "HANDLE POST #1", hasContentLength, hasTransferEncoding); var content = request.ReadBody(); switch (Mode) { case TransferMode.Default: if (Content != null) { ctx.Expect(hasContentLength, Is.True, "Missing Content-Length"); break; } else { ctx.Expect(hasContentLength, Is.False, "Content-Length header not allowed"); return(HttpResponse.CreateSuccess()); } case TransferMode.ContentLength: ctx.Expect(hasContentLength, Is.True, "Missing Content-Length"); ctx.Expect(hasTransferEncoding, Is.False, "Transfer-Encoding header not allowed"); break; case TransferMode.Chunked: if ((effectiveFlags & RequestFlags.Redirected) != 0) { goto case TransferMode.ContentLength; } ctx.Expect(hasContentLength, Is.False, "Content-Length header not allowed"); var ok = ctx.Expect(hasTransferEncoding, Is.True, "Missing Transfer-Encoding header"); if (!ok) { break; } var transferEncoding = request.Headers ["Transfer-Encoding"]; ok &= ctx.Expect(transferEncoding.ToLowerInvariant(), Is.EqualTo("chunked"), "Invalid Transfer-Encoding"); break; default: ctx.Expect(false, "Unknown TransferMode: '{0}'", Mode); return(null); } Debug(ctx, 5, "BODY", content); if ((effectiveFlags & RequestFlags.NoBody) != 0) { ctx.Expect(HttpContent.IsNullOrEmpty(content), "Must not send a body with this request."); return(null); } if (Content != null) { HttpContent.Compare(ctx, content, Content, true); } else { ctx.Expect(HttpContent.IsNullOrEmpty(content), "null or empty content"); } return(null); }
private async Task <IResponse> RequestV3(AbstractModel request, string actionName) { string endpoint = this.Endpoint; if (!string.IsNullOrEmpty(this.Profile.HttpProfile.Endpoint)) { endpoint = this.Profile.HttpProfile.Endpoint; } string httpRequestMethod = this.Profile.HttpProfile.ReqMethod; string canonicalURI = "/"; string canonicalQueryString = ""; string requestPayload = ""; string contentType = "application/x-www-form-urlencoded"; if (HttpProfile.REQ_GET.Equals(httpRequestMethod)) { Dictionary <string, string> param = new Dictionary <string, string>(); request.ToMap(param, ""); StringBuilder urlBuilder = new StringBuilder(); foreach (KeyValuePair <string, string> kvp in param) { urlBuilder.Append($"{WebUtility.UrlEncode(kvp.Key)}={WebUtility.UrlEncode(kvp.Value)}&"); } canonicalQueryString = urlBuilder.ToString().TrimEnd('&'); } else { requestPayload = JsonConvert.SerializeObject(request, Newtonsoft.Json.Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); contentType = "application/json"; } // HttpContent->StringContent will add charset to utf-8 in content-type, // which leads to authentication failure in API... string canonicalHeaders = "content-type:" + contentType + "; charset=utf-8\nhost:" + endpoint + "\n"; string signedHeaders = "content-type;host"; string hashedRequestPayload = SignHelper.SHA256Hex(requestPayload); string canonicalRequest = httpRequestMethod + "\n" + canonicalURI + "\n" + canonicalQueryString + "\n" + canonicalHeaders + "\n" + signedHeaders + "\n" + hashedRequestPayload; //Console.WriteLine(canonicalRequest); string algorithm = "TC3-HMAC-SHA256"; long timestamp = ToTimestamp() / 1000; string requestTimestamp = timestamp.ToString(); string date = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddSeconds(timestamp).ToString("yyyy-MM-dd"); string service = endpoint.Split('.')[0]; string credentialScope = date + "/" + service + "/" + "tc3_request"; string hashedCanonicalRequest = SignHelper.SHA256Hex(canonicalRequest); string stringToSign = algorithm + "\n" + requestTimestamp + "\n" + credentialScope + "\n" + hashedCanonicalRequest; //Console.WriteLine(stringToSign); byte[] tc3SecretKey = Encoding.UTF8.GetBytes("TC3" + Credential.SecretKey); byte[] secretDate = SignHelper.HmacSHA256(tc3SecretKey, Encoding.UTF8.GetBytes(date)); byte[] secretService = SignHelper.HmacSHA256(secretDate, Encoding.UTF8.GetBytes(service)); byte[] secretSigning = SignHelper.HmacSHA256(secretService, Encoding.UTF8.GetBytes("tc3_request")); byte[] signatureBytes = SignHelper.HmacSHA256(secretSigning, Encoding.UTF8.GetBytes(stringToSign)); string signature = BitConverter.ToString(signatureBytes).Replace("-", "").ToLower(); //Console.WriteLine(signature); string authorization = algorithm + " " + "Credential=" + Credential.SecretId + "/" + credentialScope + ", " + "SignedHeaders=" + signedHeaders + ", " + "Signature=" + signature; //Console.WriteLine(authorization); Dictionary <string, string> headers = new Dictionary <string, string>(); headers.Add("Authorization", authorization); headers.Add("Host", endpoint); headers.Add("Content-Type", contentType); headers.Add("X-TC-Action", actionName); headers.Add("X-TC-Timestamp", requestTimestamp); headers.Add("X-TC-Version", this.ApiVersion); headers.Add("X-TC-Region", this.Region); headers.Add("X-TC-RequestClient", this.SdkVersion); if (!string.IsNullOrEmpty(this.Credential.Token)) { headers.Add("X-TC-Token", this.Credential.Token); } HttpConnection conn = new HttpConnection( $"{this.Profile.HttpProfile.Protocol }{endpoint}", this.Profile.HttpProfile.Timeout, this.Profile.HttpProfile.WebProxy); try { if (this.Profile.HttpProfile.ReqMethod == HttpProfile.REQ_GET) { return(await conn.GetRequest(this.Path, canonicalQueryString, headers)); } else { return(await conn.PostRequest(this.Path, requestPayload, headers)); } } catch (Exception e) { throw new TencentCloudSDKException($"The request with exception: {e.Message}"); } }
protected async Task <string> InternalRequest(AbstractModel request, string actionName) { IResponse okRsp = null; string endpoint = this.Endpoint; if (!string.IsNullOrEmpty(this.Profile.HttpProfile.Endpoint)) { endpoint = this.Profile.HttpProfile.Endpoint; } Dictionary <string, string> param = new Dictionary <string, string>(); request.ToMap(param, ""); // inplace change this.FormatRequestData(actionName, param); HttpConnection conn = new HttpConnection($"{this.Profile.HttpProfile.Protocol }{endpoint}", this.Profile.HttpProfile.Timeout, this.Profile.HttpProfile.WebProxy); if ((this.Profile.HttpProfile.ReqMethod != HttpProfile.REQ_GET) && (this.Profile.HttpProfile.ReqMethod != HttpProfile.REQ_POST)) { throw new TencentCloudSDKException("Method only support (GET, POST)"); } try { if (this.Profile.HttpProfile.ReqMethod == HttpProfile.REQ_GET) { okRsp = await conn.GetRequest($"{this.Path}", param); } else if (this.Profile.HttpProfile.ReqMethod == HttpProfile.REQ_POST) { okRsp = await conn.PostRequest(this.Path, param); } } catch (Exception ex) { throw new TencentCloudSDKException($"The request with exception: {ex.Message }"); } if ((int)okRsp.Status != HTTP_RSP_OK) { throw new TencentCloudSDKException(okRsp.Status + await okRsp.Message.Content.ReadAsStringAsync()); } string strResp = null; try { strResp = await okRsp.AsString(); } catch (ApiException ex) { string responseText = await ex.Response.AsString(); throw new TencentCloudSDKException($"The API responded with HTTP {ex.Response.Status}: {responseText}"); } JsonResponseModel <JsonResponseErrModel> errResp = null; try { errResp = JsonConvert.DeserializeObject <JsonResponseModel <JsonResponseErrModel> >(strResp); } catch (JsonSerializationException e) { throw new TencentCloudSDKException(e.Message); } if (errResp.Response.Error != null) { throw new TencentCloudSDKException($"code:{errResp.Response.Error.Code} message:{errResp.Response.Error.Message} ", errResp.Response.RequestId); } return(strResp); }
public HttpSecureConnectionState(HttpConnection connection, Action<HttpConnection> callback) { Connection = connection; Callback = callback; }
public void SetConnection(HttpConnection connection) { Task.Connection = connection ?? throw new ArgumentNullException(nameof(connection)); }