static int _CreateBestHTTP_HTTPResponse(IntPtr L) { try { int count = LuaDLL.lua_gettop(L); if (count == 4) { BestHTTP.HTTPRequest arg0 = (BestHTTP.HTTPRequest)ToLua.CheckObject(L, 1, typeof(BestHTTP.HTTPRequest)); System.IO.Stream arg1 = (System.IO.Stream)ToLua.CheckObject <System.IO.Stream>(L, 2); bool arg2 = LuaDLL.luaL_checkboolean(L, 3); bool arg3 = LuaDLL.luaL_checkboolean(L, 4); BestHTTP.HTTPResponse obj = new BestHTTP.HTTPResponse(arg0, arg1, arg2, arg3); ToLua.PushObject(L, obj); return(1); } else { return(LuaDLL.luaL_throw(L, "invalid arguments to ctor method: BestHTTP.HTTPResponse.New")); } } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
void OnDownloaded(HTTPRequest req, HTTPResponse resp) { Debug.Log ("OnDownloaded"); NetworkMsgType error = NetworkMsgType.network; string message = "未知错误"; if (resp != null) { if (resp.IsSuccess) { byte[] data = resp.Data; protoBuffer.SetResMsg (data, data.Length); error = NetworkMsgType.protocol; message = "请求成功"; } else { if (resp.StatusCode == 500 || resp.StatusCode == 501 || resp.StatusCode == 503 || resp.StatusCode == 403) { message = resp.DataAsText; error = NetworkMsgType.server; } } } // return; onFinish (error, message, protoBuffer); }
/// <summary> /// Prepares the request by adding two headers to it /// </summary> public void PrepareRequest(BestHTTP.HTTPRequest request) { if (HTTPProtocolFactory.GetProtocolFromUri(request.CurrentUri) == SupportedProtocols.HTTP) { request.Uri = PrepareUri(request.Uri); } }
internal HTTPResponse(HTTPRequest request, Stream stream, bool isStreamed, bool isFromCache) { this.baseRequest = request; this.Stream = stream; this.IsStreamed = isStreamed; this.IsFromCache = isFromCache; }
public static HTTPResponse Get(SupportedProtocols protocol, HTTPRequest request, Stream stream, bool isStreamed, bool isFromCache) { switch (protocol) { case SupportedProtocols.WebSocket: return new WebSocket.WebSocketResponse(request, stream, isStreamed, isFromCache); default: return new HTTPResponse(request, stream, isStreamed, isFromCache); } }
internal WebSocketResponse(HTTPRequest request, Stream stream, bool isStreamed, bool isFromCache) : base(request, stream, isStreamed, isFromCache) { base.IsClosedManually = true; closed = false; MaxFragmentSize = UInt16.MaxValue / 2; }
/// <summary> /// Prepares the request by adding two headers to it /// </summary> public void PrepareRequest(BestHTTP.HTTPRequest request) { request.SetHeader("x-redirect-count", _connection.RedirectCount.ToString()); if (HTTPProtocolFactory.GetProtocolFromUri(request.CurrentUri) == SupportedProtocols.HTTP) { request.Uri = PrepareUri(request.Uri); } }
void OnSendRequestFinished(HTTPRequest req, HTTPResponse resp) { sendRequestQueue.Remove(req); // error reason if there is any. We will call the manager's Error function if it's not empty. string reason = string.Empty; switch (req.State) { // The request finished without any problem. case HTTPRequestStates.Finished: if (resp.IsSuccess) { HTTPManager.Logger.Information("Transport - " + this.Name, "Send - Request Finished Successfully! " + resp.DataAsText); if (!string.IsNullOrEmpty(resp.DataAsText)) { IServerMessage msg = TransportBase.Parse(Connection.JsonEncoder, resp.DataAsText); if (msg != null) Connection.OnMessage(msg); } } else reason = string.Format("Send - Request Finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2}", resp.StatusCode, resp.Message, resp.DataAsText); break; // The request finished with an unexpected error. The request's Exception property may contain more info about the error. case HTTPRequestStates.Error: reason = "Send - Request Finished with Error! " + (req.Exception != null ? (req.Exception.Message + "\n" + req.Exception.StackTrace) : "No Exception"); break; // The request aborted, initiated by the user. case HTTPRequestStates.Aborted: reason = "Send - Request Aborted!"; break; // Ceonnecting to the server is timed out. case HTTPRequestStates.ConnectionTimedOut: reason = "Send - Connection Timed Out!"; break; // The request didn't finished in the given time. case HTTPRequestStates.TimedOut: reason = "Send - Processing the request Timed Out!"; break; } if (!string.IsNullOrEmpty(reason)) Connection.Error(reason); }
public override void Stop() { HTTPManager.Heartbeats.Unsubscribe(this); if (pollRequest != null) { pollRequest.Abort(); pollRequest = null; } // Should we abort the send requests in the sendRequestQueue? }
public void PostRequest( AbstractHttpProtocol proto, Callback<NetworkMsgType, string, AbstractHttpProtocol> onFinish ) { this.protoBuffer = proto; this.onFinish = onFinish; Uri uri = new Uri (proto.GetRequestUrl()); HTTPRequest request = new HTTPRequest (uri, HTTPMethods.Post, true, true, OnDownloaded); request.ConnectTimeout = TimeSpan.FromSeconds (connect_time_out); request.Timeout = TimeSpan.FromSeconds (time_out); request.RawData = proto.postBody; request.EnableTimoutForStreaming = true; HTTPManager.SendRequest(request); }
public static HTTPResponse Get(SupportedProtocols protocol, HTTPRequest request, Stream stream, bool isStreamed, bool isFromCache) { switch (protocol) { #if !BESTHTTP_DISABLE_WEBSOCKET && (!UNITY_WEBGL || UNITY_EDITOR) case SupportedProtocols.WebSocket: return new WebSocket.WebSocketResponse(request, stream, isStreamed, isFromCache); #endif #if !BESTHTTP_DISABLE_SERVERSENT_EVENTS && (!UNITY_WEBGL || UNITY_EDITOR) case SupportedProtocols.ServerSentEvents: return new ServerSentEvents.EventSourceResponse(request, stream, isStreamed, isFromCache); #endif default: return new HTTPResponse(request, stream, isStreamed, isFromCache); } }
/// <summary> /// Called when the response downloaded, or if an error occured. /// </summary> /// <param name="request">The original request that automatically generated in the SendRequest call.</param> /// <param name="response">The response object that holds everything the server sent to us. Or null, if an error occured.</param> private void OnImageDownloaded(BestHTTP.HTTPRequest request, BestHTTP.HTTPResponse response) { if (response != null) { Debug.Log("Download finished!"); // Set the texture to the newly downloaded one this.GetComponent <GUITexture>().texture = response.DataAsTexture2D; } else { Debug.LogError("No response received: " + (request.Exception != null ? (request.Exception.Message + "\n" + request.Exception.StackTrace) : "No Exception")); } }
/// <summary> /// OSS Get /// </summary> /// <param name="url"></param> /// <param name="post"></param> /// <param name="OnRequestFinished"></param> /// <param name="token"></param> public static void OssGet(string url, KeyValuePair <string, string>[] post, OnRequestFinishedDelegate OnRequestFinished, string token = null) { BestHTTP.HTTPRequest request = new BestHTTP.HTTPRequest(new Uri(url), true, OnRequestFinished); request.Timeout = TimeSpan.FromMinutes(10); request.ConnectTimeout = TimeSpan.FromMinutes(5); if (post != null) { foreach (var item in post) { request.SetHeader(item.Key, item.Value); } } request.Send(); }
static int QPYX_get_httpReq_YXQP(IntPtr L_YXQP) { object QPYX_o_YXQP = null; try { QPYX_o_YXQP = ToLua.ToObject(L_YXQP, 1); BestHttpOperation QPYX_obj_YXQP = (BestHttpOperation)QPYX_o_YXQP; BestHTTP.HTTPRequest QPYX_ret_YXQP = QPYX_obj_YXQP.httpReq; ToLua.PushSealed(L_YXQP, QPYX_ret_YXQP); return(1); } catch (Exception QPYX_e_YXQP) { return(LuaDLL.toluaL_exception(L_YXQP, QPYX_e_YXQP, QPYX_o_YXQP, "attempt to index httpReq on a nil value")); } }
/// <summary> /// Polling transport specific connection logic. It's a regular GET request to the /connect path. /// </summary> public override void Connect() { HTTPManager.Logger.Information("Transport - " + this.Name, "Sending Open Request"); // Skip the Connecting state if we are reconnecting. If the connect succeeds, we will set the Started state directly if (this.State != TransportStates.Reconnecting) this.State = TransportStates.Connecting; RequestTypes requestType = this.State == TransportStates.Reconnecting ? RequestTypes.Reconnect : RequestTypes.Connect; var request = new HTTPRequest(Connection.BuildUri(requestType, this), HTTPMethods.Get, true, true, OnConnectRequestFinished); Connection.PrepareRequest(request, requestType); request.Send(); }
protected override void SendImpl(string json) { var request = new HTTPRequest(Connection.BuildUri(RequestTypes.Send, this), HTTPMethods.Post, true, true, OnSendRequestFinished); request.FormUsage = Forms.HTTPFormUsage.UrlEncoded; request.AddField("data", json); Connection.PrepareRequest(request, RequestTypes.Send); // Set a lower priority then the default. This way requests that are sent out alonside with SignalR sent requests can be processed sooner. request.Priority = -1; request.Send(); sendRequestQueue.Add(request); }
static int get_httpReq(IntPtr L) { object o = null; try { o = ToLua.ToObject(L, 1); BestHttpOperation obj = (BestHttpOperation)o; BestHTTP.HTTPRequest ret = obj.httpReq; ToLua.PushSealed(L, ret); return(1); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e, o, "attempt to index httpReq on a nil value")); } }
internal void Process(HTTPRequest request) { if (State == HTTPConnectionStates.Processing) throw new Exception("Connection already processing a request!"); StartTime = DateTime.MaxValue; State = HTTPConnectionStates.Processing; CurrentRequest = request; #if NETFX_CORE Windows.System.Threading.ThreadPool.RunAsync(ThreadFunc); #else //ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadFunc)); new Thread(ThreadFunc) .Start(); #endif }
static int get_InternalRequest(IntPtr L) { object o = null; try { o = ToLua.ToObject(L, 1); BestHTTP.WebSocket.WebSocket obj = (BestHTTP.WebSocket.WebSocket)o; BestHTTP.HTTPRequest ret = obj.InternalRequest; ToLua.Push(L, ret); return(1); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e, o == null ? "attempt to index InternalRequest on a nil value" : e.Message)); } }
protected void CreateRequest(string action, Action<HTTPRequest, HTTPResponse> callback, HTTPMethods methodType = HTTPMethods.Get) { request = new HTTPRequest (new Uri (_host + action), methodType, (HTTPRequest req, HTTPResponse res) => { if (interstitialLoading) { _dispatcher.Dispatch("loading_interstitial_close"); } // if finished correctly if (req.State == HTTPRequestStates.Finished) { ClearError(); callback(req, res); } // if not show an error with a retry and/or a go back to main menu else { Debug.Log (req.State); ShowError(); GameAnalytics.NewErrorEvent (GA_Error.GAErrorSeverity.GAErrorSeverityCritical , "Failed connection: " + PlayerPrefs.GetString("username") + " | " + action + " | " + req.State); } }); // add options AddOptions (); }
private static ConnectionBase FindOrCreateFreeConnection(HTTPRequest request) { ConnectionBase conn = null; List <ConnectionBase> connections; string serverUrl = GetKeyForRequest(request); if (Connections.TryGetValue(serverUrl, out connections)) { // count active connections int activeConnections = 0; for (int i = 0; i < connections.Count; ++i) { if (connections[i].IsActive) { activeConnections++; } } if (activeConnections <= MaxConnectionPerServer) { // search for a Free connection for (int i = 0; i < connections.Count && conn == null; ++i) { var tmpConn = connections[i]; if (tmpConn != null && tmpConn.IsFree && ( #if !BESTHTTP_DISABLE_PROXY !tmpConn.HasProxy || #endif tmpConn.LastProcessedUri == null || tmpConn.LastProcessedUri.Host.Equals(request.CurrentUri.Host, StringComparison.OrdinalIgnoreCase))) { conn = tmpConn; } } } } else { Connections.Add(serverUrl, connections = new List <ConnectionBase>(MaxConnectionPerServer)); } // No free connection found? if (conn == null) { // Max connection reached? if (connections.Count >= MaxConnectionPerServer) { return(null); } // if no, create a new one connections.Add(conn = CreateConnection(request, serverUrl)); } return(conn); }
internal static bool RemoveFromQueue(HTTPRequest request) { return(RequestQueue.Remove(request)); }
private static string GetKeyForRequest(HTTPRequest request) { // proxyUri + requestUri // HTTP and HTTPS needs different connections. return (request.Proxy != null ? new UriBuilder(request.Proxy.Address.Scheme, request.Proxy.Address.Host, request.Proxy.Address.Port).Uri.ToString() : string.Empty) + new UriBuilder(request.CurrentUri.Scheme, request.CurrentUri.Host, request.CurrentUri.Port).Uri.ToString(); }
/// <summary> /// Polling transport speficic function. Sends a GET request to the /poll path to receive messages. /// </summary> private void Poll() { pollRequest = new HTTPRequest(Connection.BuildUri(RequestTypes.Poll, this), HTTPMethods.Get, true, true, OnPollRequestFinished); Connection.PrepareRequest(pollRequest, RequestTypes.Poll); pollRequest.Timeout = this.PollTimeout; pollRequest.Send(); }
internal HTTPProxyResponse(HTTPRequest request, Stream stream, bool isStreamed, bool isFromCache) : base(request, stream, isStreamed, isFromCache) { }
/// <summary> /// Start to get the negotiation data. /// </summary> public void Start() { NegotiationRequest = new HTTPRequest(Connection.BuildUri(RequestTypes.Negotiate), HTTPMethods.Get, true, true, OnNegotiationRequestFinished); Connection.PrepareRequest(NegotiationRequest, RequestTypes.Negotiate); NegotiationRequest.Send(); HTTPManager.Logger.Information("NegotiationData", "Negotiation request sent"); }
internal EventSourceResponse(HTTPRequest request, Stream stream, bool isStreamed, bool isFromCache) :base(request, stream, isStreamed, isFromCache) { base.IsClosedManually = true; }
public AssetBundleDownloadFromHttp(string assetBundleName, string url, int version, int crc, int level) : base(assetBundleName) { m_url = url; string path = PathUtils.MakeFilePath(assetBundleName, PathUtils.PathType.MobileDiskWrite); FileStream stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite); HTTPRequest http = new BestHTTP.HTTPRequest(new Uri(url), HTTPMethods.Head, (req, resp) => { if (resp == null) { stream.Dispose(); return; } if (resp.StatusCode == 416) { stream.Dispose(); return; } if (resp.HasHeaderWithValue("accept-ranges", "none")) { stream.Dispose(); return; } long remoteLength = GetLength(resp); if (remoteLength <= 0) { stream.Dispose(); return; } long localLength = stream.Length; if (localLength == remoteLength) { Loom.RunAsync(() => { m_data = new byte[localLength]; stream.Read(m_data, 0, (int)localLength); stream.Dispose(); Loom.QueueOnMainThread(() => { if (m_data != null && m_data.Length > 0) { m_abcr = AssetBundle.LoadFromMemoryAsync(m_data); } m_isDownloaded = true; }); }); return; } var downloadRequest = new HTTPRequest(req.Uri, HTTPMethods.Get, true, (downloadReq, downloadResp) => { Loom.RunAsync(() => { stream.Write(downloadResp.Data, 0, downloadResp.Data.Length); stream.Flush(); long length = stream.Length; m_data = new byte[length]; stream.Seek(0, SeekOrigin.Begin); stream.Read(m_data, 0, m_data.Length); stream.Dispose(); Loom.QueueOnMainThread(() => { if (m_data != null && m_data.Length > 0) { m_abcr = AssetBundle.LoadFromMemoryAsync(m_data); } m_isDownloaded = true; }); }); }); //Debug.Log(req.Uri + "\n" + "length: " + localLength); downloadRequest.SetRangeHeader((int)localLength); downloadRequest.DisableCache = true; downloadRequest.Send(); //m_data = resp.Data; //m_isDownloaded = true; //if (m_data != null && m_data.Length > 0) //{ // m_abcr = AssetBundle.LoadFromMemoryAsync(m_data); //} }); http.DisableCache = true; http.Send(); }
internal override void Connect(Stream stream, HTTPRequest request) { // https://tools.ietf.org/html/rfc1928 // The client connects to the server, and sends a version // identifier/method selection message: // // +----+----------+----------+ // |VER | NMETHODS | METHODS | // +----+----------+----------+ // | 1 | 1 | 1 to 255 | // +----+----------+----------+ // // The VER field is set to X'05' for this version of the protocol. The // NMETHODS field contains the number of method identifier octets that // appear in the METHODS field. // var buffer = new byte[1024]; int count = 0; buffer[count++] = (byte)SOCKSVersions.V5; if (this.Credentials != null) { buffer[count++] = 0x02; // method count buffer[count++] = (byte)SOCKSMethods.UsernameAndPassword; buffer[count++] = (byte)SOCKSMethods.NoAuthenticationRequired; } else { buffer[count++] = 0x01; // method count buffer[count++] = (byte)SOCKSMethods.NoAuthenticationRequired; } if (HTTPManager.Logger.Level == Logger.Loglevels.All) { HTTPManager.Logger.Information("SOCKSProxy", string.Format("Sending method negotiation - count: {0} buffer: {1} ", count.ToString(), BufferToHexStr(buffer, count))); } // Write negotiation stream.Write(buffer, 0, count); // Read result count = stream.Read(buffer, 0, buffer.Length); if (HTTPManager.Logger.Level == Logger.Loglevels.All) { HTTPManager.Logger.Information("SOCKSProxy", string.Format("Negotiation response - count: {0} buffer: {1} ", count.ToString(), BufferToHexStr(buffer, count))); } // The server selects from one of the methods given in METHODS, and // sends a METHOD selection message: // // +----+--------+ // |VER | METHOD | // +----+--------+ // | 1 | 1 | // +----+--------+ // // If the selected METHOD is X'FF', none of the methods listed by the // client are acceptable, and the client MUST close the connection. // // The values currently defined for METHOD are: // // o X'00' NO AUTHENTICATION REQUIRED // o X'01' GSSAPI // o X'02' USERNAME/PASSWORD // o X'03' to X'7F' IANA ASSIGNED // o X'80' to X'FE' RESERVED FOR PRIVATE METHODS // o X'FF' NO ACCEPTABLE METHODS // // The client and server then enter a method-specific sub-negotiation. SOCKSVersions version = (SOCKSVersions)buffer[0]; SOCKSMethods method = (SOCKSMethods)buffer[1]; // Expected result: // 1.) Received bytes' count is 2: version + preferred method // 2.) Version must be 5 // 3.) Preferred method must NOT be 0xFF if (count != 2) { throw new Exception(string.Format("SOCKS Proxy - Expected read count: 2! count: {0} buffer: {1}" + count.ToString(), BufferToHexStr(buffer, count))); } else if (version != SOCKSVersions.V5) { throw new Exception("SOCKS Proxy - Expected version: 5, received version: " + buffer[0].ToString("X2")); } else if (method == SOCKSMethods.NoAcceptableMethods) { throw new Exception("SOCKS Proxy - Received 'NO ACCEPTABLE METHODS' (0xFF)"); } else { HTTPManager.Logger.Information("SOCKSProxy", "Method negotiation over. Method: " + method.ToString()); switch (method) { case SOCKSMethods.NoAuthenticationRequired: // nothing to do break; case SOCKSMethods.UsernameAndPassword: if (this.Credentials.UserName.Length > 255) { throw new Exception(string.Format("SOCKS Proxy - Credentials.UserName too long! {0} > 255", this.Credentials.UserName.Length.ToString())); } if (this.Credentials.Password.Length > 255) { throw new Exception(string.Format("SOCKS Proxy - Credentials.Password too long! {0} > 255", this.Credentials.Password.Length.ToString())); } // https://tools.ietf.org/html/rfc1929 : Username/Password Authentication for SOCKS V5 // Once the SOCKS V5 server has started, and the client has selected the // Username/Password Authentication protocol, the Username/Password // subnegotiation begins. This begins with the client producing a // Username/Password request: // // +----+------+----------+------+----------+ // |VER | ULEN | UNAME | PLEN | PASSWD | // +----+------+----------+------+----------+ // | 1 | 1 | 1 to 255 | 1 | 1 to 255 | // +----+------+----------+------+----------+ HTTPManager.Logger.Information("SOCKSProxy", "starting sub-negotiation"); count = 0; buffer[count++] = 0x01; // version of sub negotiation WriteString(buffer, ref count, this.Credentials.UserName); WriteString(buffer, ref count, this.Credentials.Password); if (HTTPManager.Logger.Level == Logger.Loglevels.All) { HTTPManager.Logger.Information("SOCKSProxy", string.Format("Sending username and password sub-negotiation - count: {0} buffer: {1} ", count.ToString(), BufferToHexStr(buffer, count))); } // Write negotiation stream.Write(buffer, 0, count); // Read result count = stream.Read(buffer, 0, buffer.Length); if (HTTPManager.Logger.Level == Logger.Loglevels.All) { HTTPManager.Logger.Information("SOCKSProxy", string.Format("Username and password sub-negotiation response - count: {0} buffer: {1} ", count.ToString(), BufferToHexStr(buffer, count))); } // The server verifies the supplied UNAME and PASSWD, and sends the // following response: // // +----+--------+ // |VER | STATUS | // +----+--------+ // | 1 | 1 | // +----+--------+ // A STATUS field of X'00' indicates success. If the server returns a // `failure' (STATUS value other than X'00') status, it MUST close the // connection. bool success = buffer[1] == 0; if (count != 2) { throw new Exception(string.Format("SOCKS Proxy - Expected read count: 2! count: {0} buffer: {1}" + count.ToString(), BufferToHexStr(buffer, count))); } else if (!success) { throw new Exception("SOCKS proxy: username+password authentication failed!"); } HTTPManager.Logger.Information("SOCKSProxy", "Authenticated!"); break; case SOCKSMethods.GSSAPI: throw new Exception("SOCKS proxy: GSSAPI not supported!"); case SOCKSMethods.NoAcceptableMethods: throw new Exception("SOCKS proxy: No acceptable method"); } } // The SOCKS request is formed as follows: // // +----+-----+-------+------+----------+----------+ // |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT | // +----+-----+-------+------+----------+----------+ // | 1 | 1 | X'00' | 1 | Variable | 2 | // +----+-----+-------+------+----------+----------+ // // Where: // // o VER protocol version: X'05' // o CMD // o CONNECT X'01' // o BIND X'02' // o UDP ASSOCIATE X'03' // o RSV RESERVED // o ATYP address type of following address // o IP V4 address: X'01' // o DOMAINNAME: X'03' // o IP V6 address: X'04' // o DST.ADDR desired destination address // o DST.PORT desired destination port in network octet // order count = 0; buffer[count++] = (byte)SOCKSVersions.V5; // version: 5 buffer[count++] = 0x01; // command: connect buffer[count++] = 0x00; // reserved, bust be 0x00 if (request.CurrentUri.IsHostIsAnIPAddress()) { bool isIPV4 = Extensions.Extensions.IsIpV4AddressValid(request.CurrentUri.Host); buffer[count++] = isIPV4 ? (byte)SOCKSAddressTypes.IPV4 : (byte)SOCKSAddressTypes.IPv6; var ipAddress = System.Net.IPAddress.Parse(request.CurrentUri.Host); var ipBytes = ipAddress.GetAddressBytes(); WriteBytes(buffer, ref count, ipBytes); // destination address } else { buffer[count++] = (byte)SOCKSAddressTypes.DomainName; // The first octet of the address field contains the number of octets of name that // follow, there is no terminating NUL octet. WriteString(buffer, ref count, request.CurrentUri.Host); } // destination port in network octet order buffer[count++] = (byte)((request.CurrentUri.Port >> 8) & 0xFF); buffer[count++] = (byte)(request.CurrentUri.Port & 0xFF); if (HTTPManager.Logger.Level == Logger.Loglevels.All) { HTTPManager.Logger.Information("SOCKSProxy", string.Format("Sending connect request - count: {0} buffer: {1} ", count.ToString(), BufferToHexStr(buffer, count))); } stream.Write(buffer, 0, count); count = stream.Read(buffer, 0, buffer.Length); if (HTTPManager.Logger.Level == Logger.Loglevels.All) { HTTPManager.Logger.Information("SOCKSProxy", string.Format("Connect response - count: {0} buffer: {1} ", count.ToString(), BufferToHexStr(buffer, count))); } // The SOCKS request information is sent by the client as soon as it has // established a connection to the SOCKS server, and completed the // authentication negotiations. The server evaluates the request, and // returns a reply formed as follows: // // +----+-----+-------+------+----------+----------+ // |VER | REP | RSV | ATYP | BND.ADDR | BND.PORT | // +----+-----+-------+------+----------+----------+ // | 1 | 1 | X'00' | 1 | Variable | 2 | // +----+-----+-------+------+----------+----------+ // // Where: // o VER protocol version: X'05' // o REP Reply field: // o X'00' succeeded // o X'01' general SOCKS server failure // o X'02' connection not allowed by ruleset // o X'03' Network unreachable // o X'04' Host unreachable // o X'05' Connection refused // o X'06' TTL expired // o X'07' Command not supported // o X'08' Address type not supported // o X'09' to X'FF' unassigned // o RSV RESERVED // o ATYP address type of following address // o IP V4 address: X'01' // o DOMAINNAME: X'03' // o IP V6 address: X'04' // o BND.ADDR server bound address // o BND.PORT server bound port in network octet order // // Fields marked RESERVED (RSV) must be set to X'00'. version = (SOCKSVersions)buffer[0]; SOCKSReplies reply = (SOCKSReplies)buffer[1]; // at least 10 bytes expected as a result if (count < 10) { throw new Exception(string.Format("SOCKS proxy: not enough data returned by the server. Expected count is at least 10 bytes, server returned {0} bytes! content: {1}", count.ToString(), BufferToHexStr(buffer, count))); } else if (reply != SOCKSReplies.Succeeded) { throw new Exception("SOCKS proxy error: " + reply.ToString()); } HTTPManager.Logger.Information("SOCKSProxy", "Connected!"); }
void OnDownloadProgress(HTTPRequest request, int downloaded, int length) { _progress = (downloaded / (float)length); }
public void InitDownloadHttp() { try { if (m_remoteLength > 0) { SendToLua(m_localLength, m_remoteLength); return; } string path = PathUtils.MakeFilePath("http_zip.zip", PathUtils.PathType.MobileDiskWrite); string url = GameConfig.HOST_RES() + "http_zip.zip"; FileStream stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite); HTTPRequest http = new BestHTTP.HTTPRequest(new Uri(url), HTTPMethods.Head, (req, resp) => { if (resp == null) { stream.Dispose(); return; } if (resp.StatusCode == 416) { stream.Dispose(); return; } if (resp.HasHeaderWithValue("accept-ranges", "none")) { stream.Dispose(); return; } m_remoteLength = GetLength(resp); if (m_remoteLength <= 0) { stream.Dispose(); return; } m_localLength = stream.Length; SendToLua(m_localLength, m_remoteLength); if (m_localLength == m_remoteLength) { m_zipIsOk = true; m_downloadComplated = true; StartDecompress(); return; } else { stream.Close(); if (NetSpeed.GetCurrentNetType() != JzwlNetworkInfo.TYPE_MOBILE) { StartDownloadHttp(); } } }); http.DisableCache = true; http.Send(); } catch (Exception ex) { Debug.Log(ex.Message + "\n" + ex.StackTrace); } }
private static ConnectionBase FindOrCreateFreeConnection(HTTPRequest request) { ConnectionBase conn = null; List<ConnectionBase> connections; string serverUrl = GetKeyForRequest(request); if (Connections.TryGetValue(serverUrl, out connections)) { // count active connections int activeConnections = 0; for (int i = 0; i < connections.Count; ++i) if (connections[i].IsActive) activeConnections++; if (activeConnections <= MaxConnectionPerServer) // search for a Free connection for (int i = 0; i < connections.Count && conn == null; ++i) { var tmpConn = connections[i]; if (tmpConn != null && tmpConn.IsFree && ( #if !BESTHTTP_DISABLE_PROXY !tmpConn.HasProxy || #endif tmpConn.LastProcessedUri == null || tmpConn.LastProcessedUri.Host.Equals(request.CurrentUri.Host, StringComparison.OrdinalIgnoreCase))) conn = tmpConn; } } else Connections.Add(serverUrl, connections = new List<ConnectionBase>(MaxConnectionPerServer)); // No free connection found? if (conn == null) { // Max connection reached? if (connections.Count >= MaxConnectionPerServer) return null; // if no, create a new one connections.Add(conn = CreateConnection(request, serverUrl)); } return conn; }
private static string GetKeyForRequest(HTTPRequest request) { if (request.CurrentUri.IsFile) return request.CurrentUri.ToString(); // proxyUri + requestUri // HTTP and HTTPS needs different connections. return #if !BESTHTTP_DISABLE_PROXY (request.Proxy != null ? new UriBuilder(request.Proxy.Address.Scheme, request.Proxy.Address.Host, request.Proxy.Address.Port).Uri.ToString() : string.Empty) + #endif new UriBuilder(request.CurrentUri.Scheme, request.CurrentUri.Host, request.CurrentUri.Port).Uri.ToString(); }
public static HTTPRequest SendRequest(HTTPRequest request) { lock (Locker) { Setup(); // TODO: itt meg csak adja hozza egy sorhoz, es majd a LateUpdate-ben hivodjon a SendRequestImpl. // Igy ha egy callback-ben kuldenenk ugyanarra a szerverre request-et, akkor feltudjuk hasznalni az elozo connection-t. if (IsCallingCallbacks) { request.State = HTTPRequestStates.Queued; RequestQueue.Add(request); } else SendRequestImpl(request); return request; } }
protected override void ThreadFunc(object param) { bool flag = false; bool flag2 = false; RetryCauses none = RetryCauses.None; try { if (!base.HasProxy && base.CurrentRequest.HasProxy) { base.Proxy = base.CurrentRequest.Proxy; } if (!this.TryLoadAllFromCache()) { if ((this.Client != null) && !this.Client.IsConnected()) { this.Close(); } do { if (none == RetryCauses.Reconnect) { this.Close(); Thread.Sleep(100); } base.LastProcessedUri = base.CurrentRequest.CurrentUri; none = RetryCauses.None; this.Connect(); if (base.State == HTTPConnectionStates.AbortRequested) { throw new Exception("AbortRequested"); } if (!base.CurrentRequest.DisableCache) { HTTPCacheService.SetHeaders(base.CurrentRequest); } bool flag3 = false; try { this.Client.NoDelay = base.CurrentRequest.TryToMinimizeTCPLatency; base.CurrentRequest.SendOutTo(this.Stream); flag3 = true; } catch (Exception exception) { this.Close(); if ((base.State == HTTPConnectionStates.TimedOut) || (base.State == HTTPConnectionStates.AbortRequested)) { throw new Exception("AbortRequested"); } if (flag || base.CurrentRequest.DisableRetry) { throw exception; } flag = true; none = RetryCauses.Reconnect; } if (flag3) { bool flag4 = this.Receive(); if ((base.State == HTTPConnectionStates.TimedOut) || (base.State == HTTPConnectionStates.AbortRequested)) { throw new Exception("AbortRequested"); } if ((!flag4 && !flag) && !base.CurrentRequest.DisableRetry) { flag = true; none = RetryCauses.Reconnect; } if (base.CurrentRequest.Response != null) { if (base.CurrentRequest.IsCookiesEnabled) { CookieJar.Set(base.CurrentRequest.Response); } switch (base.CurrentRequest.Response.StatusCode) { case 0x12d: case 0x12e: case 0x133: case 0x134: if (base.CurrentRequest.RedirectCount < base.CurrentRequest.MaxRedirects) { HTTPRequest currentRequest = base.CurrentRequest; currentRequest.RedirectCount++; string firstHeaderValue = base.CurrentRequest.Response.GetFirstHeaderValue("location"); if (string.IsNullOrEmpty(firstHeaderValue)) { throw new MissingFieldException($"Got redirect status({base.CurrentRequest.Response.StatusCode.ToString()}) without 'location' header!"); } Uri redirectUri = this.GetRedirectUri(firstHeaderValue); if (HTTPManager.Logger.Level == Loglevels.All) { HTTPManager.Logger.Verbose("HTTPConnection", string.Format("{0} - Redirected to Location: '{1}' redirectUri: '{1}'", base.CurrentRequest.CurrentUri.ToString(), firstHeaderValue, redirectUri)); } if (!base.CurrentRequest.CallOnBeforeRedirection(redirectUri)) { HTTPManager.Logger.Information("HTTPConnection", "OnBeforeRedirection returned False"); } else { base.CurrentRequest.RemoveHeader("Host"); base.CurrentRequest.SetHeader("Referer", base.CurrentRequest.CurrentUri.ToString()); base.CurrentRequest.RedirectUri = redirectUri; base.CurrentRequest.Response = null; bool flag5 = true; base.CurrentRequest.IsRedirected = flag5; flag2 = flag5; } } break; case 0x191: { string str = DigestStore.FindBest(base.CurrentRequest.Response.GetHeaderValues("www-authenticate")); if (!string.IsNullOrEmpty(str)) { Digest orCreate = DigestStore.GetOrCreate(base.CurrentRequest.CurrentUri); orCreate.ParseChallange(str); if (((base.CurrentRequest.Credentials != null) && orCreate.IsUriProtected(base.CurrentRequest.CurrentUri)) && (!base.CurrentRequest.HasHeader("Authorization") || orCreate.Stale)) { none = RetryCauses.Authenticate; } } break; } case 0x197: if (base.CurrentRequest.HasProxy) { string str2 = DigestStore.FindBest(base.CurrentRequest.Response.GetHeaderValues("proxy-authenticate")); if (!string.IsNullOrEmpty(str2)) { Digest orCreate = DigestStore.GetOrCreate(base.CurrentRequest.Proxy.Address); orCreate.ParseChallange(str2); if (((base.CurrentRequest.Proxy.Credentials != null) && orCreate.IsUriProtected(base.CurrentRequest.Proxy.Address)) && (!base.CurrentRequest.HasHeader("Proxy-Authorization") || orCreate.Stale)) { none = RetryCauses.ProxyAuthenticate; } } } break; } this.TryStoreInCache(); if ((base.CurrentRequest.Response == null) || !base.CurrentRequest.Response.IsClosedManually) { bool flag6 = (base.CurrentRequest.Response == null) || base.CurrentRequest.Response.HasHeaderWithValue("connection", "close"); bool flag7 = !base.CurrentRequest.IsKeepAlive; if (flag6 || flag7) { this.Close(); } else if (base.CurrentRequest.Response != null) { List <string> headerValues = base.CurrentRequest.Response.GetHeaderValues("keep-alive"); if ((headerValues != null) && (headerValues.Count > 0)) { if (this.KeepAlive == null) { this.KeepAlive = new KeepAliveHeader(); } this.KeepAlive.Parse(headerValues); } } } } } }while (none != RetryCauses.None); } } catch (TimeoutException exception2) { base.CurrentRequest.Response = null; base.CurrentRequest.Exception = exception2; base.CurrentRequest.State = HTTPRequestStates.ConnectionTimedOut; this.Close(); } catch (Exception exception3) { if (base.CurrentRequest != null) { if (base.CurrentRequest.UseStreaming) { HTTPCacheService.DeleteEntity(base.CurrentRequest.CurrentUri, true); } base.CurrentRequest.Response = null; switch (base.State) { case HTTPConnectionStates.AbortRequested: case HTTPConnectionStates.Closed: base.CurrentRequest.State = HTTPRequestStates.Aborted; goto Label_0685; case HTTPConnectionStates.TimedOut: base.CurrentRequest.State = HTTPRequestStates.TimedOut; goto Label_0685; } base.CurrentRequest.Exception = exception3; base.CurrentRequest.State = HTTPRequestStates.Error; } Label_0685: this.Close(); } finally { if (base.CurrentRequest != null) { object locker = HTTPManager.Locker; lock (locker) { if (((base.CurrentRequest != null) && (base.CurrentRequest.Response != null)) && base.CurrentRequest.Response.IsUpgraded) { base.State = HTTPConnectionStates.Upgraded; } else { base.State = !flag2 ? ((this.Client != null) ? HTTPConnectionStates.WaitForRecycle : HTTPConnectionStates.Closed) : HTTPConnectionStates.Redirected; } if ((base.CurrentRequest.State == HTTPRequestStates.Processing) && ((base.State == HTTPConnectionStates.Closed) || (base.State == HTTPConnectionStates.WaitForRecycle))) { if (base.CurrentRequest.Response != null) { base.CurrentRequest.State = HTTPRequestStates.Finished; } else { base.CurrentRequest.Exception = new Exception($"Remote server closed the connection before sending response header! Previous request state: {base.CurrentRequest.State.ToString()}. Connection state: {base.State.ToString()}"); base.CurrentRequest.State = HTTPRequestStates.Error; } } if (base.CurrentRequest.State == HTTPRequestStates.ConnectionTimedOut) { base.State = HTTPConnectionStates.Closed; } base.LastProcessTime = DateTime.UtcNow; if (base.OnConnectionRecycled != null) { base.RecycleNow(); } } HTTPCacheService.SaveLibrary(); CookieJar.Persist(); } } }
public SimpleHttpReq(System.Uri uri, int reqId = int.MinValue) { ReqId = reqId; Req = new HTTPRequest(uri); }
internal override void Connect(Stream stream, HTTPRequest request) { bool isSecure = HTTPProtocolFactory.IsSecureProtocol(request.CurrentUri); if (!this.IsTransparent || (isSecure && this.NonTransparentForHTTPS)) { using (var bufferedStream = new WriteOnlyBufferedStream(stream, HTTPRequest.UploadChunkSize)) using (var outStream = new BinaryWriter(bufferedStream, Encoding.UTF8)) { bool retry; do { // If we have to because of a authentication request, we will switch it to true retry = false; string connectStr = string.Format("CONNECT {0}:{1} HTTP/1.1", request.CurrentUri.Host, request.CurrentUri.Port.ToString()); HTTPManager.Logger.Information("HTTPProxy", "Sending " + connectStr, request.Context); outStream.SendAsASCII(connectStr); outStream.Write(HTTPRequest.EOL); outStream.SendAsASCII("Proxy-Connection: Keep-Alive"); outStream.Write(HTTPRequest.EOL); outStream.SendAsASCII("Connection: Keep-Alive"); outStream.Write(HTTPRequest.EOL); outStream.SendAsASCII(string.Format("Host: {0}:{1}", request.CurrentUri.Host, request.CurrentUri.Port.ToString())); outStream.Write(HTTPRequest.EOL); // Proxy Authentication if (this.Credentials != null) { switch (this.Credentials.Type) { case AuthenticationTypes.Basic: // With Basic authentication we don't want to wait for a challenge, we will send the hash with the first request outStream.Write(string.Format("Proxy-Authorization: {0}", string.Concat("Basic ", Convert.ToBase64String(Encoding.UTF8.GetBytes(this.Credentials.UserName + ":" + this.Credentials.Password)))).GetASCIIBytes()); outStream.Write(HTTPRequest.EOL); break; case AuthenticationTypes.Unknown: case AuthenticationTypes.Digest: var digest = DigestStore.Get(this.Address); if (digest != null) { string authentication = digest.GenerateResponseHeader(request, this.Credentials, true); if (!string.IsNullOrEmpty(authentication)) { string auth = string.Format("Proxy-Authorization: {0}", authentication); if (HTTPManager.Logger.Level <= Logger.Loglevels.Information) { HTTPManager.Logger.Information("HTTPProxy", "Sending proxy authorization header: " + auth, request.Context); } var bytes = auth.GetASCIIBytes(); outStream.Write(bytes); outStream.Write(HTTPRequest.EOL); BufferPool.Release(bytes); } } break; } } outStream.Write(HTTPRequest.EOL); // Make sure to send all the wrote data to the wire outStream.Flush(); request.ProxyResponse = new HTTPResponse(request, stream, false, false); // Read back the response of the proxy if (!request.ProxyResponse.Receive(-1, true)) { throw new Exception("Connection to the Proxy Server failed!"); } if (HTTPManager.Logger.Level <= Logger.Loglevels.Information) { HTTPManager.Logger.Information("HTTPProxy", "Proxy returned - status code: " + request.ProxyResponse.StatusCode + " message: " + request.ProxyResponse.Message + " Body: " + request.ProxyResponse.DataAsText, request.Context); } switch (request.ProxyResponse.StatusCode) { // Proxy authentication required // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.8 case 407: { string authHeader = DigestStore.FindBest(request.ProxyResponse.GetHeaderValues("proxy-authenticate")); if (!string.IsNullOrEmpty(authHeader)) { var digest = DigestStore.GetOrCreate(this.Address); digest.ParseChallange(authHeader); if (this.Credentials != null && digest.IsUriProtected(this.Address) && (!request.HasHeader("Proxy-Authorization") || digest.Stale)) { retry = true; } } if (!retry) { throw new Exception(string.Format("Can't authenticate Proxy! Status Code: \"{0}\", Message: \"{1}\" and Response: {2}", request.ProxyResponse.StatusCode, request.ProxyResponse.Message, request.ProxyResponse.DataAsText)); } break; } default: if (!request.ProxyResponse.IsSuccess) { throw new Exception(string.Format("Proxy returned Status Code: \"{0}\", Message: \"{1}\" and Response: {2}", request.ProxyResponse.StatusCode, request.ProxyResponse.Message, request.ProxyResponse.DataAsText)); } break; } } while (retry); }// using outstream } }
// https://library.vuforia.com/articles/Solution/How-To-Use-the-Vuforia-Web-Services-API.htm#How-To-Update-a-Target IEnumerator PutUpdateTarget(bool updateImage = false) { Debug.Log("CustomMessage: PutUpdateTarget()"); // Setting up query. string requestPath = "/targets/" + currentImageData.UniqueTargetId; string serviceURI = url + requestPath; string httpAction = "PUT"; string contentType = "application/json"; string date = string.Format("{0:r}", DateTime.Now.ToUniversalTime()); string metadataStr = jsonData; byte[] metadata = System.Text.ASCIIEncoding.ASCII.GetBytes(metadataStr); // Create new model to prepare for sending. PostNewTrackableRequest model = new PostNewTrackableRequest(); model.name = targetName; model.width = 64.0f; model.application_metadata = System.Convert.ToBase64String(metadata); if (updateImage) { // Create texture and encode pixels to base64. Texture2D tex = new Texture2D(texture.width, texture.height, TextureFormat.RGB24, false); tex.SetPixels(texture.GetPixels()); tex.Apply(); byte[] image = tex.EncodeToPNG(); model.image = System.Convert.ToBase64String(image); } // Convert model to json. string requestBody = JsonUtility.ToJson(model); // Create ContentMD5. MD5 md5 = MD5.Create(); var contentMD5bytes = md5.ComputeHash(System.Text.Encoding.ASCII.GetBytes(requestBody)); System.Text.StringBuilder sb = new System.Text.StringBuilder(); for (int i = 0; i < contentMD5bytes.Length; i++) { sb.Append(contentMD5bytes[i].ToString("x2")); } string contentMD5 = sb.ToString(); string stringToSign = string.Format("{0}\n{1}\n{2}\n{3}\n{4}", httpAction, contentMD5, contentType, date, requestPath); // Build signature. HMACSHA1 sha1 = new HMACSHA1(System.Text.Encoding.ASCII.GetBytes(secret_key)); byte[] sha1Bytes = System.Text.Encoding.ASCII.GetBytes(stringToSign); MemoryStream stream = new MemoryStream(sha1Bytes); byte[] sha1Hash = sha1.ComputeHash(stream); string signature = System.Convert.ToBase64String(sha1Hash); Debug.Log("<color=green>Signature: " + signature + "</color>"); // Build Http Request. BestHTTP.HTTPRequest request = new BestHTTP.HTTPRequest(new Uri(serviceURI)); request.MethodType = BestHTTP.HTTPMethods.Put; request.RawData = Encoding.UTF8.GetBytes(requestBody); request.AddHeader("Authorization", string.Format("VWS {0}:{1}", access_key, signature)); request.AddHeader("Content-Type", contentType); request.AddHeader("Date", date); request.Send(); yield return(StartCoroutine(request)); switch (request.State) { case BestHTTP.HTTPRequestStates.Error: Debug.Log("request error: " + request.Exception.Message); string errorText = request.Exception.Message; PrintStatusText("Exception: " + errorText); break; case BestHTTP.HTTPRequestStates.Finished: // There is an error if (request.Response.StatusCode != 200) { Debug.Log("request error: " + request.Response.Message); string result_code = JsonUtility.FromJson <VWSResponse>(request.Response.DataAsText).result_code; // The target is still being processed in Vuforia API. if (result_code == "TargetStatusNotSuccess") { PrintStatusText("Error: Profile is still being processed in Vuforia!"); } else { PrintStatusText("Error: " + result_code); } } else { Debug.Log("request success"); PrintStatusText("Saved!"); if (rescanCloudAfterEdit) { // We disable cloud tracking for x seconds. The reason why we do this is because it takes time for // Vuforia to actually delete the record. If we continue cloud tracking, it would retrack the record. DisableCloudTracking(2f); // To get all the tracked targets. For testing. // IEnumerable<Vuforia.ObjectTarget> obj = Vuforia.TrackerManager.Instance.GetTracker<Vuforia.ObjectTracker>().GetTargetFinder<Vuforia.ImageTargetFinder>().GetObjectTargets(); // IEnumerator myEnum = obj.GetEnumerator(); // while(myEnum.MoveNext()){ // print(myEnum.Current); // } // Clear local copy. Vuforia.TrackerManager.Instance.GetTracker <Vuforia.ObjectTracker>().GetTargetFinder <Vuforia.ImageTargetFinder>().ClearTrackables(false); } else { // Since the image is saved to the cloud, we can change the local copy. currentImageData.MetaData = metadataStr; currentImageData.TargetName = targetName; // Force update of target info. cloudContentManager.HandleTargetFinderResult(currentImageData); // The only issue with this method is we do not know the new tracking rating of the copy. // However, since our version of profiler does not show tracking rating, it should work fine. // Also, if the new image fails the processor on Vuforia's side, it wouldn't make sense to // change the local copy's data. However, it would be more convenient for the user to see // the new updated version. Therefore, when changing the local copy, we are assuming the // new image to be processed successfully. } // Close edit menu. ToggleEditMenu(); } break; } // Enable buttons. deleteDeleteButton.interactable = true; putEditButton.interactable = true; editButton.interactable = true; }
public override void PrepareRequest(HTTPRequest request) { // Set up Content-Type header for the request request.SetHeader("Content-Type", "multipart/form-data; boundary=\"" + Boundary + "\""); }
private void OnNegotiationRequestFinished(HTTPRequest req, HTTPResponse resp) { NegotiationRequest = null; switch (req.State) { case HTTPRequestStates.Finished: if (resp.IsSuccess) { HTTPManager.Logger.Information("NegotiationData", "Negotiation data arrived: " + resp.DataAsText); int idx = resp.DataAsText.IndexOf("{"); if (idx < 0) { RaiseOnError("Invalid negotiation text: " + resp.DataAsText); return; } var Negotiation = Parse(resp.DataAsText.Substring(idx)); if (Negotiation == null) { RaiseOnError("Parsing Negotiation data failed: " + resp.DataAsText); return; } if (OnReceived != null) { OnReceived(this); OnReceived = null; } } else RaiseOnError(string.Format("Negotiation request finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2} Uri: {3}", resp.StatusCode, resp.Message, resp.DataAsText, req.CurrentUri)); break; case HTTPRequestStates.Error: RaiseOnError(req.Exception != null ? (req.Exception.Message + " " + req.Exception.StackTrace) : string.Empty); break; default: RaiseOnError(req.State.ToString()); break; } }
internal abstract void Connect(Stream stream, HTTPRequest request);
void OnPollRequestFinished(HTTPRequest req, HTTPResponse resp) { // When Stop() called on the transport. // In Stop() we set the pollRequest to null, but a new poll request can be made after a quick reconnection, and there is a chanse that // in this handler function we can null out the new request. So we return early here. if (req.State == HTTPRequestStates.Aborted) { HTTPManager.Logger.Warning("Transport - " + this.Name, "Poll - Request Aborted!"); return; } // Set the pollRequest to null, now we can send out a new one pollRequest = null; // error reason if there is any. We will call the manager's Error function if it's not empty. string reason = string.Empty; switch (req.State) { // The request finished without any problem. case HTTPRequestStates.Finished: if (resp.IsSuccess) { HTTPManager.Logger.Information("Transport - " + this.Name, "Poll - Request Finished Successfully! " + resp.DataAsText); IServerMessage msg = TransportBase.Parse(Connection.JsonEncoder, resp.DataAsText); if (msg != null) { Connection.OnMessage(msg); MultiMessage multiple = msg as MultiMessage; if (multiple != null && multiple.PollDelay.HasValue) PollDelay = multiple.PollDelay.Value; LastPoll = DateTime.UtcNow; } } else reason = string.Format("Poll - Request Finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2}", resp.StatusCode, resp.Message, resp.DataAsText); break; // The request finished with an unexpected error. The request's Exception property may contain more info about the error. case HTTPRequestStates.Error: reason = "Poll - Request Finished with Error! " + (req.Exception != null ? (req.Exception.Message + "\n" + req.Exception.StackTrace) : "No Exception"); break; // Ceonnecting to the server is timed out. case HTTPRequestStates.ConnectionTimedOut: reason = "Poll - Connection Timed Out!"; break; // The request didn't finished in the given time. case HTTPRequestStates.TimedOut: reason = "Poll - Processing the request Timed Out!"; break; } if (!string.IsNullOrEmpty(reason)) Connection.Error(reason); }
internal static bool RemoveFromQueue(HTTPRequest request) { return RequestQueue.Remove(request); }
// https://library.vuforia.com/articles/Solution/How-To-Use-the-Vuforia-Web-Services-API.htm#How-To-Delete-a-Target IEnumerator DeleteTarget() { Debug.Log("CustomMessage: DeleteTarget()"); // Setting up query. string requestPath = "/targets/" + currentImageData.UniqueTargetId; string serviceURI = url + requestPath; string httpAction = "DELETE"; string contentType = ""; string date = string.Format("{0:r}", DateTime.Now.ToUniversalTime()); // Create ContentMD5. MD5 md5 = MD5.Create(); var contentMD5bytes = md5.ComputeHash(System.Text.Encoding.ASCII.GetBytes("")); System.Text.StringBuilder sb = new System.Text.StringBuilder(); for (int i = 0; i < contentMD5bytes.Length; i++) { sb.Append(contentMD5bytes[i].ToString("x2")); } string contentMD5 = sb.ToString(); string stringToSign = string.Format("{0}\n{1}\n{2}\n{3}\n{4}", httpAction, contentMD5, contentType, date, requestPath); // Build signature. HMACSHA1 sha1 = new HMACSHA1(System.Text.Encoding.ASCII.GetBytes(secret_key)); byte[] sha1Bytes = System.Text.Encoding.ASCII.GetBytes(stringToSign); MemoryStream stream = new MemoryStream(sha1Bytes); byte[] sha1Hash = sha1.ComputeHash(stream); string signature = System.Convert.ToBase64String(sha1Hash); Debug.Log("<color=green>Signature: " + signature + "</color>"); // Build Http Request. BestHTTP.HTTPRequest request = new BestHTTP.HTTPRequest(new Uri(serviceURI)); request.MethodType = BestHTTP.HTTPMethods.Delete; request.RawData = Encoding.UTF8.GetBytes(""); request.AddHeader("Authorization", string.Format("VWS {0}:{1}", access_key, signature)); request.AddHeader("Content-Type", contentType); request.AddHeader("Date", date); request.Send(); yield return(StartCoroutine(request)); switch (request.State) { case BestHTTP.HTTPRequestStates.Error: Debug.Log("request error: " + request.Exception.Message); string errorText = request.Exception.Message; PrintStatusText("Exception: " + errorText); editButton.interactable = true; break; case BestHTTP.HTTPRequestStates.Finished: // There is an error if (request.Response.StatusCode != 200) { Debug.Log("request error: " + request.Response.Message); string result_code = JsonUtility.FromJson <VWSResponse>(request.Response.DataAsText).result_code; // The target is still being processed in Vuforia API. if (result_code == "TargetStatusProcessing") { PrintStatusText("Error: Profile is still being processed in Vuforia!"); } else { PrintStatusText("Error: " + result_code); } editButton.interactable = true; } else { Debug.Log("request success"); PrintStatusText("Deleted!"); // We disable cloud tracking for x seconds. The reason why we do this is because it takes time for // Vuforia to actually delete the record. If we continue cloud tracking, it would retrack the record. DisableCloudTracking(2f); // To get all the tracked targets. For testing. // IEnumerable<Vuforia.ObjectTarget> obj = Vuforia.TrackerManager.Instance.GetTracker<Vuforia.ObjectTracker>().GetTargetFinder<Vuforia.ImageTargetFinder>().GetObjectTargets(); // IEnumerator myEnum = obj.GetEnumerator(); // while(myEnum.MoveNext()){ // print(myEnum.Current); // } // Clear local copy. Vuforia.TrackerManager.Instance.GetTracker <Vuforia.ObjectTracker>().GetTargetFinder <Vuforia.ImageTargetFinder>().ClearTrackables(false); // Vuforia.TrackerManager.Instance.GetTracker<Vuforia.ObjectTracker>().GetTargetFinder<Vuforia.ImageTargetFinder>().Stop(); // Vuforia.TrackerManager.Instance.GetTracker<Vuforia.ObjectTracker>().GetTargetFinder<Vuforia.ImageTargetFinder>().StartRecognition(); // Close edit menu. ToggleEditMenu(); // Enable the upload button. This is needed because the tracker is disabled, and therefore, events are not being triggered // which in turn stops our handler from setting button states. uploadButton.interactable = true; } break; } // Enable buttons. deleteDeleteButton.interactable = true; putEditButton.interactable = true; }
private static void SendRequestImpl(HTTPRequest request) { ConnectionBase conn = FindOrCreateFreeConnection(request); if (conn != null) { // found a free connection: put it in the ActiveConnection list(they will be checked periodically in the OnUpdate call) if (ActiveConnections.Find((c) => c == conn) == null) ActiveConnections.Add(conn); FreeConnections.Remove(conn); request.State = HTTPRequestStates.Processing; request.Prepare(); // then start process the request conn.Process(request); } else { // If no free connection found and creation prohibited, we will put back to the queue request.State = HTTPRequestStates.Queued; RequestQueue.Add(request); } }
internal HTTPResponse(HTTPRequest request, Stream stream, bool isStreamed, bool isFromCache) { this.baseRequest = request; this.Stream = stream; this.IsStreamed = isStreamed; #if !BESTHTTP_DISABLE_CACHING this.IsFromCache = isFromCache; #endif this.IsClosedManually = false; }
/// <summary> /// Factory method to create a concrete connection object. /// </summary> private static ConnectionBase CreateConnection(HTTPRequest request, string serverUrl) { if (request.CurrentUri.IsFile) return new FileConnection(serverUrl); return new HTTPConnection(serverUrl); }
internal WebSocketResponse(HTTPRequest request, Stream stream, bool isStreamed, bool isFromCache) : base(request, stream, isStreamed, isFromCache) { closed = false; ClosedCount = 0; MinClosedCount = 1; MaxFragmentSize = UInt16.MaxValue / 2; }
/// <summary> /// Will return the ConnectionBase object that processing the given request. /// </summary> internal static ConnectionBase GetConnectionWith(HTTPRequest request) { lock (Locker) { for (int i = 0; i < ActiveConnections.Count; ++i) { var connection = ActiveConnections[i]; if (connection.CurrentRequest == request) return connection; } return null; } }
/// <summary> /// 加载版本文件 /// </summary> /// <param name="onComplete"></param> /// <param name="onError"></param> public void LoadVersion(Action onComplete, Action onError) { string url = GameConfig.HOST_RES() + GameConfig.LOCAL_HTTP_CONFIG_FILE + "?t=" + TimeUtils.CurLocalTimeMilliSecond(); BestHTTP.HTTPRequest request = new BestHTTP.HTTPRequest(new Uri(url), (req, resp) => { if (resp != null) { Loom.RunAsync(() => { m_httpConfig = JsonFx.Json.JsonReader.Deserialize <VersionBundleConfig>(resp.DataAsText); M_CacheHttpBundles(); string infoFilePath = PathUtils.MakeFilePath(GameConfig.LOCAL_DOWNLOAD_INFO_FILE, PathUtils.PathType.MobileDiskWrite); if (File.Exists(infoFilePath)) { using (FileStream infoStream = File.OpenRead(infoFilePath)) { if (infoStream != null) { byte[] index = new byte[infoStream.Length]; infoStream.Read(index, 0, index.Length); string content = System.Text.Encoding.Default.GetString(index); DownloadFileInfo downloadFileInfo = JsonFx.Json.JsonReader.Deserialize <DownloadFileInfo>(content); ResHelper.Instance().lastZipIndex = downloadFileInfo.totalSize; for (int i = 0; i < downloadFileInfo.ids.Length; i++) { ResHelper.Instance().downloadedFiles.Add(downloadFileInfo.ids[i], 1); } } } } if (GameConfig.useLocalRes) { m_version = new VersionConfig(); m_version.version = "0.0.0"; Loom.QueueOnMainThread(() => { if (onComplete != null) { onComplete(); } }); } else { url = GameConfig.HOST_RES_ZIP() + "zip/" + GameConfig.LOCAL_VERSION_FILE + "?t=" + TimeUtils.CurLocalTimeMilliSecond(); BestHTTP.HTTPRequest zipRequest = new BestHTTP.HTTPRequest(new Uri(url), (zipReq, zipResp) => { if (zipResp != null) { m_version = JsonFx.Json.JsonReader.Deserialize <VersionConfig>(zipResp.DataAsText); if (null != onComplete) { onComplete(); } } else { if (null != onError) { onError(); } } }); zipRequest.Send(); } }); } else { if (null != onError) { onError(); } } }); request.DisableCache = true; request.Send(); }
internal HTTPProxyResponse(HTTPRequest request, Stream stream, bool isStreamed, bool isFromCache) :base(request, stream, isStreamed, isFromCache) { }
public static SecureProtocol.Org.BouncyCastle.Crypto.Tls.AbstractTlsClient DefaultTlsClientFactory(HTTPRequest request, List <string> protocols) { // http://tools.ietf.org/html/rfc3546#section-3.1 // -It is RECOMMENDED that clients include an extension of type "server_name" in the client hello whenever they locate a server by a supported name type. // -Literal IPv4 and IPv6 addresses are not permitted in "HostName". // User-defined list has a higher priority List <string> hostNames = request.CustomTLSServerNameList; // If there's no user defined one and the host isn't an IP address, add the default one if ((hostNames == null || hostNames.Count == 0) && !request.CurrentUri.IsHostIsAnIPAddress()) { hostNames = new List <string>(1); hostNames.Add(request.CurrentUri.Host); } return(new SecureProtocol.Org.BouncyCastle.Crypto.Tls.LegacyTlsClient(request.CurrentUri, request.CustomCertificateVerifyer == null ? new SecureProtocol.Org.BouncyCastle.Crypto.Tls.AlwaysValidVerifyer() : request.CustomCertificateVerifyer, request.CustomClientCredentialsProvider, hostNames, protocols)); }