示例#1
0
        protected async Task <JObject> PostJObject(string path, JObject obj)
        {
            var payload = new StringContent(StdJson.ObjectToString(obj), Encoding.UTF8);

            HttpResponseMessage response = null;

            try {
                response = await client.PostAsync(path, payload);
            }
            catch (TaskCanceledException) {
                OnConnectionBroken();
                throw new ConnectivityException("Time out");
            }
            catch (Exception exp) {
                OnConnectionBroken();
                throw new ConnectivityException(exp.Message, exp);
            }

            using (response) {
                if (response.IsSuccessStatusCode)
                {
                    try {
                        string content = await response.Content.ReadAsStringAsync();

                        if (string.IsNullOrEmpty(content))
                        {
                            return(new JObject());
                        }
                        return(StdJson.JObjectFromString(content));
                    }
                    catch (Exception exp) {
                        OnConnectionBroken();
                        throw new ConnectivityException(exp.Message, exp);
                    }
                }
                else
                {
                    await ThrowError(response);

                    return(null); // never come here
                }
            }
        }
示例#2
0
        protected async Task ThrowError(HttpResponseMessage response)
        {
            string content = null;

            try {
                content = await response.Content.ReadAsStringAsync();
            }
            catch (Exception) {}

            JObject errObj = null;

            try {
                errObj = StdJson.JObjectFromString(content);
            }
            catch (Exception) {}

            const string PropertyError = "error";

            if (errObj == null || errObj.Property(PropertyError) == null)
            {
                string errMsg = string.IsNullOrWhiteSpace(content) ? response.StatusCode.ToString() : content;
                OnConnectionBroken();
                throw new ConnectivityException(errMsg);
            }
            else
            {
                bool sessionInvalid = GetBoolPropertyOrDefault(errObj, "sessionInvalid", false);
                if (sessionInvalid)
                {
                    string errMsg = GetStringPropertyOrDefault(errObj, "error", "Session expired");
                    OnConnectionBroken();
                    throw new ConnectivityException(errMsg);
                }
                else
                {
                    string errMsg = GetStringPropertyOrDefault(errObj, PropertyError, response.StatusCode.ToString());
                    throw new RequestException(errMsg);
                }
            }
        }