Example #1
0
        /// <summary>
        /// put 对象
        /// </summary>
        /// <param name="url">远程地址</param>
        /// <param name="key">文件路径 无/ </param>
        /// <param name="file"></param>
        public void PutObject(string url, string key, byte[] file, UnityAction <HTTPRequest, HTTPResponse> complete = null)
        {
            CheckCosKey(() =>
            {
                string _url = url + key;

                Debug.LogFormat("[QCloudCos].PutObject url  {0} . ", _url);

                HTTPRequest request = new HTTPRequest(new Uri(_url), HTTPMethods.Put, (req, resp) =>
                {
                    if (resp.StatusCode == 200)
                    {
                        Debug.LogFormat("[QCloudCos].PutObject complete  {0} . ", _url);
                    }
                    else
                    {
                        Debug.LogErrorFormat("[QCloudCos].PutObject code error   url :''{0}' , code : '{1}' , data :'{2}' . ", _url, resp.StatusCode, resp.DataAsText);
                    }
                    if (complete != null)
                    {
                        complete.Invoke(req, resp);
                    }
                });
                string sign = GetSign("put", "/" + key, "", "");
                request.AddHeader("x-cos-security-token", cosKeyData.sessionToken);
                request.AddHeader("Authorization", sign);
                request.AddBinaryData("file", file);
                request.OnUploadProgress = OnUploadProgressCallback;
                request.Send();
            });
        }
Example #2
0
    void SendEmail()
    {
        HTTPRequest request = new HTTPRequest(new Uri(api + "/api/mail/messages/" + message_id + "/send")
                                              , HTTPMethods.Post, SendEmainRequestFinished);

        request.AddHeader("Content-Type", "application/json");
        request.AddHeader("Accept", "application/json");

        // 设置地址

        if (CheckEmailStrEasy(_emailAddress))
        {
            var fromJson = @"
            {
                ""to""     : [{""email"" : """ +
                           _emailAddress
                           + @"""}]}";

            request.RawData = Encoding.UTF8.GetBytes(fromJson);
            request.Send();
        }
        else
        {
            _onSendEmailError.Invoke("Email address is INVALID!");
        }

        //string address = "*****@*****.**";
    }
Example #3
0
    public void Post(string url, string postData, HttpManager.Callback callback)
    {
        //没有联网
        if (Application.internetReachability == NetworkReachability.NotReachable)
        {
            callback(HttpManager.EMPTY, 0, HttpManager.ERROR_NOT_REACHABLE);
            return;
        }
        //url错误
        if (string.IsNullOrEmpty(url))
        {
            callback(HttpManager.EMPTY, 0, HttpManager.ERROR_INVALID_URL);
            return;
        }
        HTTPRequest request = NewRequest(url, HTTPMethods.Post, callback);

        request.AddHeader(HttpManager.ACCEPT_ENCODING, HttpManager.GZIP);
        request.AddHeader(HttpManager.CONTENT_TYPE, HttpManager.JSON_TYPE);
        request.RawData = Encoding.UTF8.GetBytes(postData);
        //返回一个代表该值的新TimeSpan对象
        request.ConnectTimeout = TimeSpan.FromSeconds(timeoutSec);
        request.Timeout        = TimeSpan.FromSeconds(timeoutSec);
        request.IsKeepAlive    = isKeepAlive;
        request.DisableRetry   = !enableRetry;
        //request.UseAlternateSSL = UseAlternateSSL(url);

        request.Send();
    }
Example #4
0
    public static void QueryUtxos(string address, Action <BitIndexUTXO[]> next)
    {
        // https://api.bitindex.network/api/v3/main/addrs/utxo
        var queryEndpoint = BitIndexEndpoint + "main/addrs/utxo";

        // TODO: Implement a timeout

        var request = new HTTPRequest(new Uri(queryEndpoint), HTTPMethods.Post, true,
                                      (r, queryResponse) =>
        {
            if (queryResponse.IsSuccess)
            {
                var utxos = JsonConvert.DeserializeObject <BitIndexUTXO[]>(
                    queryResponse.DataAsText);
                //Debug.Log( $"Found {utxos.Length} utxos" );
                next(utxos);
            }
            else
            {
                Debug.LogError($"BitIndex query not successful. Endpoint:{queryEndpoint}, Address:{address}");
                // TODO: when this happens ensure we try again or show an error - instead of assuming the identity has no utxos
                next(null);
            }
        });

        var data = $"{{\"addrs\":\"{address}\"}}";

        request.RawData = Encoding.UTF8.GetBytes(data);
        request.AddHeader("Content-Type", "application/json");
        request.AddHeader("api_key", BitIndexApiKey); // API key
        request.Send();
    }
Example #5
0
        // Token: 0x06005877 RID: 22647 RVA: 0x001EA460 File Offset: 0x001E8860
        private IEnumerator UploadMiniLogCoroutine()
        {
            UnityEngine.Debug.Log("Generating mini-log for upload...");
            List <string> list = this.GatherCurrentStateInfo();
            int           num  = 0;

            foreach (string text in list)
            {
                num += text.Length;
            }
            VRCLog.JSONLog jsonlog = new VRCLog.JSONLog();
            List <string>  list2   = this.uploadLog.CopyToArray().ToList <string>();
            int            num2    = list2.Aggregate(0, (int a, string s) => a + s.Length);

            while (num2 > 1024 && list2.Count != 0)
            {
                num2 -= list2.First <string>().Length;
                list2.RemoveAt(0);
            }
            int           capacity      = this.currentUploadLogSize + num + 1000;
            StringBuilder stringBuilder = new StringBuilder(capacity);
            string        str           = "(Steam)";

            stringBuilder.AppendLine("Mini-log uploaded, VRChat v" + jsonlog.version + " " + str);
            stringBuilder.AppendLine("Reason: " + this.uploadLogReason);
            stringBuilder.AppendLine(string.Empty);
            stringBuilder.AppendLine("... <log snippet starts here> ...");
            foreach (string value in list2)
            {
                stringBuilder.AppendLine(value);
            }
            stringBuilder.AppendLine("... <end log> ...\r\n");
            stringBuilder.AppendLine("===== Current state ==========");
            foreach (string value2 in list)
            {
                stringBuilder.AppendLine(value2);
            }
            jsonlog.logs = stringBuilder.ToString();
            UnityEngine.Debug.Log("Uploading mini-log to http://api.vrchat.cloud/api/1/error (" + jsonlog.logs.Length + " bytes) ...");
            HTTPRequest httprequest = new HTTPRequest(new Uri("http://api.vrchat.cloud/api/1/error"), HTTPMethods.Post, delegate(HTTPRequest req, HTTPResponse resp)
            {
                UnityEngine.Debug.Log(string.Concat(new object[]
                {
                    "Upload mini log HTTP response: \r\n[",
                    resp.StatusCode,
                    "] ",
                    resp.Message
                }));
                this.FinishMiniLogUpload();
            });

            httprequest.ConnectTimeout = TimeSpan.FromSeconds(20.0);
            httprequest.Timeout        = TimeSpan.FromSeconds(60.0);
            httprequest.RawData        = Encoding.UTF8.GetBytes(JsonUtility.ToJson(jsonlog));
            httprequest.AddHeader("Content-Type", "application/json");
            httprequest.AddHeader("Content-Length", httprequest.RawData.Length.ToString());
            httprequest.Send();
            yield break;
        }
Example #6
0
        private void setupHeaders(HTTPRequest hr)
        {
            hr.AddHeader("charset", "utf-8");
            hr.AddHeader("Content-Type", "application/json");
            string auth = authorizationFunc();

            if (!string.IsNullOrWhiteSpace(auth))
            {
                hr.AddHeader("Authorization", auth);
            }
        }
Example #7
0
        private HTTPRequest RequestCreate(Uri uri, HTTPMethods method, OnRequestFinishedDelegate callback)
        {
            HTTPRequest request = new HTTPRequest(
                uri: uri,
                methodType: method,
                isKeepAlive: true,
                disableCache: true,
                callback: callback
                );

            request.AddHeader("Authorization", this.AccessToken);
            request.AddHeader("UserID", this.UserID);
            return(request);
        }
 internal void SetUpRevalidationHeaders(HTTPRequest request)
 {
     if (IsExists())
     {
         if (!string.IsNullOrEmpty(ETag))
         {
             request.AddHeader("If-None-Match", ETag);
         }
         if (!string.IsNullOrEmpty(LastModified))
         {
             request.AddHeader("If-Modified-Since", LastModified);
         }
     }
 }
Example #9
0
        public static HTTPRequest HttpsImagePost(string uri, byte[] data, OnRequestFinishedDelegate onRequestFinishedDelegate)
        {
            HTTPRequest httpRequest = new HTTPRequest(new Uri(uri), HTTPMethods.Post, onRequestFinishedDelegate);

            httpRequest.UseAlternateSSL    = true;
            httpRequest.StreamFragmentSize = 100 * 1024;

            httpRequest.AddHeader("did", SystemInfoUtil.getDeviceUniqueIdentifier());
            httpRequest.AddHeader("md5at", GameCache.Instance.strToken);
            httpRequest.AddField("user_id", $"{GameCache.Instance.nUserId}");
            httpRequest.AddBinaryData("file", data, "picture.png", "image/png");
            // Log.Debug(httpRequest.DumpHeaders());
            return(httpRequest.Send());
        }
Example #10
0
    void JsonAsyncInternal <SendT, RecvT>(System.Uri uri, string packet_namespace, SendT packet, Action <SendT, RecvT> callback, bool use_crc)
        where SendT : class
        where RecvT : class
    {
        if (uri == null)
        {
            throw new System.Exception("Please call CS_Client.InitServer");
        }

        PacketCore _PacketCore = new PacketCore();

        _PacketCore.Name = typeof(SendT).FullName;

        if (_PacketCore.Name.StartsWith(packet_namespace) == false)
        {
            throw new System.Exception(string.Format("Packet namesapce fault({0}) : {1}", packet_namespace, _PacketCore.Name));
        }

        _PacketCore.Data = JsonConvert.SerializeObject(packet, Formatting.None, NetworkCore.PacketUtil.json_ops);

        HTTPRequest request = new HTTPRequest(uri, HTTPMethods.Post, new Handler <SendT, RecvT>(this, callback, packet).handle);

        foreach (var header in m_Headers)
        {
            request.AddHeader(header.Key, header.Value);
        }
        request.RawData = System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(_PacketCore, Formatting.None, NetworkCore.PacketUtil.json_ops));

        Debug.Log(string.Format("[Packet:{0},{2}] {1}", _PacketCore.Name, _PacketCore.Data, SendIndex));
        if (PostCallback != null && callback != null)
        {
            Networking.Instance.Block();
        }

        if (use_crc == true && SendIndex > 0)
        {
            uint checksum = Octodiff.Core.Adler32RollingChecksum.CalculateChecksum(System.Text.Encoding.UTF8.GetBytes(_PacketCore.Name));
            checksum = Octodiff.Core.Adler32RollingChecksum.Add(checksum, System.Text.Encoding.UTF8.GetBytes(_PacketCore.Data));
            checksum = Octodiff.Core.Adler32RollingChecksum.Add(checksum, BitConverter.GetBytes(AccountIdx));
            checksum = Octodiff.Core.Adler32RollingChecksum.Add(checksum, BitConverter.GetBytes(AccessToken));
            checksum = Octodiff.Core.Adler32RollingChecksum.Add(checksum, BitConverter.GetBytes(SendIndex));
            checksum = Octodiff.Core.Adler32RollingChecksum.Add(checksum, BitConverter.GetBytes(checksum));
            request.AddHeader("Checksum", checksum.ToString());
            ++SendIndex;
        }

        request.Send();
    }
Example #11
0
        private HTTPRequest RequestCreateToJson(Uri uri, HTTPMethods method, OnRequestFinishedDelegate callback, string jstring)
        {
            HTTPRequest request = new HTTPRequest(
                uri: uri,
                methodType: method,
                isKeepAlive: true,
                disableCache: true,
                callback: callback
                );

            request.RawData = ConvertToByteArray(jstring, Encoding.UTF8);
            request.AddHeader("UserID", this.UserID);
            request.AddHeader("Authorization", this.AccessToken);
            request.AddHeader("content-type", "application/json");
            return(request);
        }
Example #12
0
    void SubmitOnClick()
    {
        foreach (InputField e in required)
        {
            function.RequiredInputOnEndEdit(e);
        }
        foreach (Text e in warning)
        {
            if (e.IsActive())
            {
                return;
            }
        }
        if (function.InputFieldRequired(required))
        {
            HTTPRequest request = new HTTPRequest(new Uri(data.IP + "/updateUser"), HTTPMethods.Post, (req, res) => {
                switch (req.State)
                {
                case HTTPRequestStates.Finished:
                    Debug.Log("Successfully save!");
                    HTTPRequest request_getUser = new HTTPRequest(new Uri(data.IP + "/getUserByAccount?account=" + data.m_user.getUsername()), HTTPMethods.Get, (req_user, res_user) =>
                    {
                        JsonData json = JsonMapper.ToObject(res_user.DataAsText);
                        Debug.Log(res_user.DataAsText);
                        data.m_user.setId((long)json["id"]);
                        data.m_user.setUsername((string)json["username"]);
                        data.m_user.setNickname((string)json["nickname"]);
                        data.m_user.setPassword((string)json["password"]);
                        data.m_user.setFirstname((string)json["firstname"]);
                        data.m_user.setLastname((string)json["lastname"]);
                        data.m_user.setPhone((string)json["phone"]);
                        data.m_user.setGender((bool)json["gender"]);
                        data.m_user.setEmail((string)json["email"]);
                        GameObject.Find("Canvas/cover").SetActive(false);
                        GameObject.Find("Canvas/password_box").SetActive(false);
                    }).Send();
                    break;

                default:
                    Debug.Log("Error!Status code:" + res.StatusCode);
                    break;
                }
            });
            request.AddHeader("Content-Type", "application/json");

            JsonData newUser = new JsonData();
            newUser["id"]        = data.m_user.getId();
            newUser["username"]  = data.m_user.getUsername();
            newUser["password"]  = function.EncryptWithMD5(new_password.text);
            newUser["nickname"]  = data.m_user.getNickname();
            newUser["gender"]    = data.m_user.getGender();
            newUser["phone"]     = data.m_user.getPhone();
            newUser["email"]     = data.m_user.getEmail();
            newUser["firstname"] = data.m_user.getFirstname();
            newUser["lastname"]  = data.m_user.getLastname();
            newUser["enabled"]   = true;
            request.RawData      = System.Text.Encoding.UTF8.GetBytes(newUser.ToJson());
            request.Send();
        }
    }
Example #13
0
    public void Get(string url, HttpManager.Callback callback)
    {
        //没有联网
        if (Application.internetReachability == NetworkReachability.NotReachable)
        {
            callback(HttpManager.EMPTY, 0, HttpManager.ERROR_NOT_REACHABLE);
            return;
        }

        //url不合法
        if (string.IsNullOrEmpty(url))
        {
            callback(HttpManager.EMPTY, 0, HttpManager.ERROR_INVALID_URL);
            return;
        }
        HTTPRequest request = NewRequest(url, HTTPMethods.Get, callback);

        request.AddHeader(HttpManager.ACCEPT_ENCODING, HttpManager.GZIP);
        request.ConnectTimeout = TimeSpan.FromSeconds(timeoutSec);
        request.Timeout        = TimeSpan.FromSeconds(timeoutSec);
        request.IsKeepAlive    = isKeepAlive;
        request.DisableRetry   = !enableRetry;

        request.Send();
    }
Example #14
0
    public static IEnumerator Match_Create(string sessionKey, string matchName, string map, int gameMode, int playerLimit, int timeLimit, int scoreLimit, string password, bool isTest, Match_Create_Delegate callback)
    {
        Match_Create p = new Match_Create();

        HTTPRequest httpRequest = new HTTPRequest(new Uri(url + "/match/create/"), HTTPMethods.Post, (request, response) =>
        {
            Debug.Log("Match Created: " + response.DataAsText);
            p       = JsonConvert.DeserializeObject <Match_Create>(response.DataAsText);
            MatchID = p.MatchID;
        });

        httpRequest.AddHeader("x-session-key", sessionKey);
        httpRequest.AddField("name", matchName);
        httpRequest.AddField("map", map);
        httpRequest.AddField("gameMode", gameMode.ToString());
        httpRequest.AddField("playerLimit", playerLimit.ToString());
        httpRequest.AddField("timeLimit", timeLimit.ToString());
        httpRequest.AddField("scoreLimit", scoreLimit.ToString());
        httpRequest.AddField("password", password);
        httpRequest.AddField("isTest", (isTest ? 1 : 0).ToString());
        httpRequest.DisableCache = true;
        httpRequest.Send();
        yield return(httpRequest);

        callback(p);
    }
        public void initialize(string titleID, string CSVkeysToQuery, int aboveVersion, string sessionTicket)
        {
            request = new HTTPRequest(new System.Uri("https://" + titleID + ".playfabapi.com/Client/GetUserData"), HTTPMethods.Post);
            request.AddHeader("X-Authentication", sessionTicket);
            request.ConnectTimeout = TimeSpan.FromSeconds(timeBeforeTimeout);
            request.Timeout        = TimeSpan.FromSeconds(timeBeforeTimeout * 3);
            request._showDebugInfo = showDebugInfo;
            request.FormUsage      = BestHTTP.Forms.HTTPFormUsage.App_JSON;

            StringBuilder sbuilder = new StringBuilder("");

            string[] strings = CSVkeysToQuery.Split(',');

            sbuilder.Append("[");
            for (int i = 0; i < strings.Length; i++)
            {
                if (i > 0)
                {
                    sbuilder.Append(",");
                }

                sbuilder.Append(quotedString(strings[i]));
            }
            sbuilder.Append("]");
            request.AddField(quotedString("keys"), sbuilder.ToString());
            request.AddField(quotedString("IfChangedFromDataVersion"), aboveVersion.ToString());
        }
Example #16
0
        /// <summary>
        /// 領取獎勵或刪除郵件 - 發送要求
        /// </summary>
        public void GetMailRewardOrDelete(GameObject _mail)
        {
            SlotSoundManager.bSndRef.PlaySoundEffect(ReferenceCenter.Ref.CommonMu.Container, SlotSoundManager.eAudioClip.Snd_ComClick1.ToString());
            currentMail = _mail;

            MailBean bean = currentMail.GetComponent <MailBean>();

            //先檢查有沒有上鎖,如果有上鎖且type為0,則不允許刪除
            if (bean.type == 0 && bean.isLock == true)
            {
                if (mMessageBoxEvent != null)
                {
                    mMessageBoxEvent("郵件已上鎖");
                }
                return;
            }

            Uri         path    = new Uri(uri_GetReward);
            HTTPRequest request = new HTTPRequest(path, HTTPMethods.Post, OnGetMailRewardFinished);

            Dictionary <string, object> req = new Dictionary <string, object>();

            req.Add("AccountName", mAccount);
            req.Add("guid", mGuid);
            req.Add("mailNumber", currentMail.GetComponent <MailBean>().mailNumber);

            request.AddHeader("Content-Type", "application/json");
            request.RawData = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(req));
            request.Send();
            mask.SetActive(true);
        }
Example #17
0
        /// <summary>
        /// Set a memory in your story
        /// </summary>
        /// <param name="token">Provide the token of the play-through where the memory should be changed.</param>
        /// <param name="recallValue">The recall value of the memory.</param>
        /// <param name="saveValue">The new value of the memory.</param>
        /// <param name="callback">Called when the mood has successfully been set.</param>
        public static void SetMemory(string token, string recallValue, string saveValue, Action callback = null)
        {
            var memory = new SetMemoryParams(recallValue, saveValue);

            var request = new HTTPRequest(
                new Uri($"{BaseUrl}/play/set-memory/"), HTTPMethods.Post, (
                    (originalRequest, response) =>
            {
                if (!response.IsSuccess)
                {
                    Debug.LogError("Error:" + originalRequest.Response.DataAsText);
                    return;
                }

                CharismaLogger.Log($"Set memory - '{memory.memoryRecallValue}' with value '{memory.saveValue}'");
                callback?.Invoke();
            }))
            {
                RawData = Encoding.UTF8.GetBytes(CharismaUtilities.ToJson(memory))
            };

            request.SetHeader("Authorization", $"Bearer {token}");
            request.AddHeader("Content-Type", "application/json");
            request.UseAlternateSSL = true;
            request.Send();
        }
Example #18
0
    public void sendAction()
    {
        GetComponent <Animator>().Play("Click");

        if (buttonType == FLOOR_BUTTON_TYPE.YES || buttonType == FLOOR_BUTTON_TYPE.NO)
        {
            GameObject.Find("Debug Text").GetComponent <Text>().text += "Setting Position \n";

            HTTPRequest request = new HTTPRequest(new Uri("http://run-west.att.io/d9576f027ee8f/6e9234f387c9/9c7023eee2b3b23/in/flow/action"), HTTPMethods.Put, actionSentCallback);

            JSONClass data = new JSONClass();

            data["value"] = ((int)buttonType).ToString();

            request.AddHeader("Content-Type", "application/json");
            //request.AddHeader("X-M2X-KEY", "9fc7996ea7f03fccc6ef3978f2a4d012");
            request.RawData = Encoding.UTF8.GetBytes(data.ToString());
            request.Send();
        }
        else
        {
            HTTPRequest request = new HTTPRequest(new Uri("http://run-west.att.io/d9576f027ee8f/6e9234f387c9/9c7023eee2b3b23/in/flow/dlswitch"), HTTPMethods.Put, actionSentCallback);

            JSONClass data = new JSONClass();

            data["value"] = (dlSwitch).ToString();

            request.AddHeader("Content-Type", "application/json");
            //request.AddHeader("X-M2X-KEY", "9fc7996ea7f03fccc6ef3978f2a4d012");
            request.RawData = Encoding.UTF8.GetBytes(data.ToString());
            request.Send();
        }
    }
Example #19
0
        /// <summary>
        /// Set the mood of a Character in your story.
        /// </summary>
        /// <param name="token">Provide the token of the play-through where a characters mood should be set.</param>
        /// <param name="characterName">The name of the character who's mood should be set.</param>
        /// <param name="mood">The mood to update to.</param>
        /// <param name="callback">Called when the mood has successfully been set.</param>
        public static void SetMood(string token, string characterName, Mood mood, Action callback = null)
        {
            if (mood == null || characterName == null)
            {
                Debug.LogError("Charisma: You need to provide both a character name and a character mood modifier.");
                return;
            }

            var newMood = new SetMoodParams(characterName, mood);

            CharismaLogger.Log($"Setting new mood for {characterName}: CharismaUtilities.ToJson(newMood)");

            var request = new HTTPRequest(
                new Uri($"{BaseUrl}/play/set-mood"), HTTPMethods.Post, (
                    (originalRequest, response) =>
            {
                if (!response.IsSuccess)
                {
                    Debug.LogError("Error:" + originalRequest.Response.DataAsText);
                    return;
                }

                CharismaLogger.Log($"Updated mood of '{characterName}'");

                callback?.Invoke();
            }))
            {
                RawData = Encoding.UTF8.GetBytes(CharismaUtilities.ToJson(newMood))
            };

            request.SetHeader("Authorization", $"Bearer {token}");
            request.AddHeader("Content-Type", "application/json");
            request.UseAlternateSSL = true;
            request.Send();
        }
Example #20
0
    protected void performRequest(string partialUrl, JSONNode parametersObject, bool isPost)
    {
        string url = Config.BASE_URL + partialUrl;

        if (!isPost)
        {
            // TODO add url parameters
        }
        if (debug)
        {
            Debug.Log("Performing request for the url: " + url);
        }
        HTTPRequest request = new HTTPRequest(new Uri(url), isPost ? HTTPMethods.Post : HTTPMethods.Get, OnRequestFinished);

        if (isPost)
        {
            string postParameters = parametersObject.ToString();
            if (debug)
            {
                Debug.Log("Parsed parameters for request are: " + postParameters);
            }
            request.RawData = Encoding.UTF8.GetBytes(postParameters);
            request.AddHeader("Content-Type", "application/json");
        }
        request.Send();
    }
Example #21
0
    void ButtonLoginOnClick()
    {
        string email    = MyWindow.window.GetInputAccount();
        string password = MyWindow.window.GetInputPassword();

        if (Validation())
        {
            password = EncryptionPass(password);
            HTTPRequest request = new HTTPRequest(new Uri(GlobalConst.UserLoginPath), onRequestFinished);
            request.MethodType = BestHTTP.HTTPMethods.Post;
            request.AddHeader("Content-Type", "application/json;charset=utf-8");
            //request.AddHeader("Accept", "*/*");
            User user = User.CreateInstance("User") as User;
            //user = MyWindow.user;
            UserLogin userlogin = new UserLogin(email, password, GlobalConst.ClientFlag + "-" + user.deviceFlag, GlobalConst.ClientVersion);
            string    parmJson  = JsonConvert.SerializeObject(userlogin);
            Debug.Log("Json: " + parmJson);
            byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(parmJson);
            request.RawData = data;

            request.Send();
        }
        else
        {
            Debug.Log("登录格式错误");
        }
        email    = "";
        password = "";
    }
        public async void Refresh()
        {
            if (Application.platform == RuntimePlatform.IPhonePlayer)
            {
                TimerComponent iOSTimerComponent = Game.Scene.GetComponent <TimerComponent>();
                while (true)
                {
                    if (UnityEngine.Application.internetReachability != NetworkReachability.NotReachable)
                    {
                        break;
                    }
                    else
                    {
                        await iOSTimerComponent.WaitAsync(200);
                    }
                }
            }

            string switchUrl = GlobalConfigComponent.Instance.GlobalProto.NetLineSwitchUrl;

            if (!string.IsNullOrEmpty(switchUrl))
            {
                HTTPRequest httpRequest = new HTTPRequest(new Uri(switchUrl), HTTPMethods.Post, ResponseDelegate);
                httpRequest.UseAlternateSSL = true;
                httpRequest.AddHeader("Content-Type", "application/json");
                httpRequest.Send();
            }
        }
Example #23
0
    public static void QueryAddressDetails(string address, Action <BitIndexAddressDetails> next)
    {
        var queryEndpoint = BitIndexEndpoint + "main/addr/" + address;
        var request       = new HTTPRequest(new Uri(queryEndpoint), HTTPMethods.Get,
                                            (r, queryResponse) =>
        {
            if (queryResponse.IsSuccess)
            {
                try
                {
                    var details = JsonConvert.DeserializeObject <BitIndexAddressDetails>(
                        queryResponse.DataAsText);
                    next(details);
                }
                catch (Exception e)
                {
                    Debug.LogError($"{e.GetType()}: {e.Message}");
                }
            }
            else
            {
                Debug.LogError("BitIndex query not successful");
                next(new BitIndexAddressDetails());
            }
        });

        request.AddHeader("api_key", BitIndexApiKey); // API key
        request.Send();
    }
Example #24
0
        private void AddHeaders(HTTPRequest request, Dictionary <string, string> headers)
        {
            foreach (KeyValuePair <string, string> pair in globalHeaders)
            {
                request.AddHeader(pair.Key, pair.Value);
            }

            if (headers == null)
            {
                return;
            }

            foreach (KeyValuePair <string, string> pair in headers)
            {
                request.AddHeader(pair.Key, pair.Value);
            }
        }
Example #25
0
    void SubmitOnClick()
    {
        foreach (InputField e in required)
        {
            function.RequiredInputOnEndEdit(e);
        }
        foreach (Text e in warning)
        {
            if (e.IsActive())
            {
                return;
            }
        }
        if (function.InputFieldRequired(required))
        {
            HTTPRequest request = new HTTPRequest(new Uri(data.IP + "/saveGarden"), HTTPMethods.Post, (req, res) => {
                switch (req.State)
                {
                case HTTPRequestStates.Finished:
                    Debug.Log(res.DataAsText);
                    GameObject.Find("Canvas/cover").SetActive(false);
                    GameObject.Find("Canvas/garden_box").SetActive(false);
                    m_garden temp = new m_garden();
                    temp.setId(long.Parse(res.DataAsText));
                    temp.setName(garden_name.text);
                    temp.setLength(int.Parse(length.text));
                    temp.setWidth(int.Parse(width.text));
                    temp.setIdealTemperature(float.Parse(temperature.text));
                    temp.setIdealHumidity(float.Parse(humidity.text));
                    data.m_user.addGardens(temp);
                    Dropdown.OptionData newOption = new Dropdown.OptionData();
                    newOption.text = garden_name.text;
                    List <Dropdown.OptionData> newOptions = new List <Dropdown.OptionData>();
                    newOptions.Add(newOption);
                    GameObject.Find("Canvas/gardens").GetComponent <Dropdown>().AddOptions(newOptions);
                    GameObject.Find("Canvas/gardens").GetComponent <Dropdown>().value = GameObject.Find("Canvas/gardens").GetComponent <Dropdown>().options.Count - 1;
                    break;

                default:
                    Debug.Log("Error!Status code:" + res.StatusCode);
                    break;
                }
            });
            request.AddHeader("Content-Type", "application/json");

            JsonData newGarden = new JsonData();
            newGarden["userId"]           = data.m_user.getId();
            newGarden["width"]            = width.text;
            newGarden["length"]           = length.text;
            newGarden["name"]             = garden_name.text;
            newGarden["idealTemperature"] = temperature.text;
            newGarden["idealWetness"]     = humidity.text;
            request.RawData = System.Text.Encoding.UTF8.GetBytes(newGarden.ToJson());

            request.Send();
        }
    }
Example #26
0
    public void talkToMe(string myResult)
    {
        myPath = "https://api.dialogflow.com/v1/query?v=##########&contexts=shop&lang=en&query=" + myResult + "&sessionId=######&timezone=America/Los_Angeles";

        HTTPRequest request = new HTTPRequest(new System.Uri(myPath), HTTPMethods.Get, OnRequestFinished);

        request.AddHeader("Authorization", "Bearer ########################");
        request.Send();
    }
Example #27
0
    public static void Spend(this Transaction txn, Action <string> a)
    {
        var txnReportRequest = new HTTPRequest(
            new Uri(TxnBroadcastEndpoint), HTTPMethods.Post,
            (txnR, txnResponse) =>
        {
            try
            {
                var response = JsonConvert.DeserializeAnonymousType(txnResponse.DataAsText,
                                                                    new { Success = false, R = "", Message = "" });
                if (!response.Success)
                {
                    Debug.LogError("Spend response was unsuccessful - " + response.Message);
                    Debug.LogError(txnResponse.DataAsText);
                    throw new SpendUTXOException(response.Message);
                }

                var hashRegex = new Regex(@"^([A-Fa-f0-9]{64})$");
                if (hashRegex.IsMatch(response.R))
                {
                    a(response.R);
                }
                else
                {
                    Debug.LogError("Failed spending utxo, return hash wasn't an hash");
                    Debug.LogError(txnResponse.DataAsText);
                    throw new SpendUTXOException(txnResponse.DataAsText);
                }
            }
            catch (Exception e)
            {
                if (txnResponse != null)
                {
                    Debug.LogError("Fatal error: " + txnResponse.DataAsText);
                }
                else
                {
                    Debug.LogError("Failed to spend transaction");
                    Debug.LogError(txnR.Exception.Message);
                }

                Debug.LogError($"{e.GetType()}: {e.Message}");

                ModalDialog.Instance.CallbackYes.AddListener(() => { SceneManager.LoadScene("Main"); });
                ModalDialog.Instance.Show("Failed to spend UTXO",
                                          $"{e.GetType()}: {e.Message}",
                                          "Ok");

                //Debug.LogError(JsonConvert.SerializeObject(txn));
                //Debug.LogError($"{{\"tx\":\"{txn.ToHex()}\"}}");
            }
        });

        txnReportRequest.AddHeader("Content-Type", "application/json");
        txnReportRequest.RawData = Encoding.UTF8.GetBytes($"{{\"tx\":\"{txn.ToHex()}\"}}");
        txnReportRequest.Send();
    }
Example #28
0
        public static HTTPRequest HttpsPost(string uri, string json, OnRequestFinishedDelegate onRequestFinishedDelegate)
        {
            HTTPRequest httpRequest = new HTTPRequest(new Uri(uri), HTTPMethods.Post, onRequestFinishedDelegate);

            httpRequest.UseAlternateSSL = true;

            httpRequest.AddHeader("Content-Type", "application/json");
            httpRequest.AddHeader("did", SystemInfoUtil.getDeviceUniqueIdentifier());
            httpRequest.AddHeader("md5at", GameCache.Instance.strToken);
            byte[] bytes = json.ToUtf8();
            string sh2sg = encrypt(bytes);

            httpRequest.AddHeader("sh2sg", sh2sg);
            httpRequest.RawData = bytes;

            // Log.Debug(httpRequest.DumpHeaders());
            return(httpRequest.Send());
        }
Example #29
0
        public static void RequestUsernameExists(string username, string email, OnRequestFinishedDelegate callback)
        {
            HTTPRequest request = new HTTPRequest(new Uri($"https://dev-api.qmedia.com.br/api/player/exists/username/{username}"), (req, res) =>
            {
                if (res.DataAsText == "false")
                {
                    APIService.RequestEmailExists(email, callback);
                }
                else
                {
                    Debug.Log("Usuário existente");
                }
            });

            request.AddHeader("accept", "text/json");
            request.AddHeader("q-imei", SystemInfo.deviceUniqueIdentifier);
            request.Send();
        }
Example #30
0
    public void GetUserInfo()
    {
        if (!IsLoggedin())
        {
            return;
        }
        HTTPRequest getInfoReq = new HTTPRequest(new Uri(GlobalConst.USERPATH), OnGetInfoFinished);

        getInfoReq.AddHeader("Content-Type", "application/json;charset=utf-8");
    }
        /// <summary>
        /// This will start the permessage-deflate negotiation process.
        /// <seealso cref="http://tools.ietf.org/html/rfc7692#section-5.1"/>
        /// </summary>
        public void AddNegotiation(HTTPRequest request)
        {
            // The default header value that we will send out minimum.
            string headerValue = "permessage-deflate";


            // http://tools.ietf.org/html/rfc7692#section-7.1.1.1
            // A client MAY include the "server_no_context_takeover" extension parameter in an extension negotiation offer.  This extension parameter has no value.
            // By including this extension parameter in an extension negotiation offer, a client prevents the peer server from using context takeover.
            // If the peer server doesn't use context takeover, the client doesn't need to reserve memory to retain the LZ77 sliding window between messages.
            if (this.ServerNoContextTakeover)
                headerValue += "; server_no_context_takeover";


            // http://tools.ietf.org/html/rfc7692#section-7.1.1.2
            // A client MAY include the "client_no_context_takeover" extension parameter in an extension negotiation offer.
            // This extension parameter has no value.  By including this extension parameter in an extension negotiation offer,
            // a client informs the peer server of a hint that even if the server doesn't include the "client_no_context_takeover"
            // extension parameter in the corresponding extension negotiation response to the offer, the client is not going to use context takeover.
            if (this.ClientNoContextTakeover)
                headerValue += "; client_no_context_takeover";

            // http://tools.ietf.org/html/rfc7692#section-7.1.2.1
            // By including this parameter in an extension negotiation offer, a client limits the LZ77 sliding window size that the server
            // will use to compress messages.If the peer server uses a small LZ77 sliding window to compress messages, the client can reduce the memory needed for the LZ77 sliding window.
            if (this.ServerMaxWindowBits != ZlibConstants.WindowBitsMax)
                headerValue += "; server_max_window_bits=" + this.ServerMaxWindowBits.ToString();
            else
                // Absence of this parameter in an extension negotiation offer indicates that the client can receive messages compressed using an LZ77 sliding window of up to 32,768 bytes.
                this.ServerMaxWindowBits = ZlibConstants.WindowBitsMax;

            // http://tools.ietf.org/html/rfc7692#section-7.1.2.2
            // By including this parameter in an offer, a client informs the peer server that the client supports the "client_max_window_bits"
            // extension parameter in an extension negotiation response and, optionally, a hint by attaching a value to the parameter.
            if (this.ClientMaxWindowBits != ZlibConstants.WindowBitsMax)
                headerValue += "; client_max_window_bits=" + this.ClientMaxWindowBits.ToString();
            else
            {
                headerValue += "; client_max_window_bits";

                // If the "client_max_window_bits" extension parameter in an extension negotiation offer has a value, the parameter also informs the
                // peer server of a hint that even if the server doesn't include the "client_max_window_bits" extension parameter in the corresponding
                // extension negotiation response with a value greater than the one in the extension negotiation offer or if the server doesn't include
                // the extension parameter at all, the client is not going to use an LZ77 sliding window size greater than the size specified
                // by the value in the extension negotiation offer to compress messages.
                this.ClientMaxWindowBits = ZlibConstants.WindowBitsMax;
            }

            // Add the new header to the request.
            request.AddHeader("Sec-WebSocket-Extensions", headerValue);
        }