Esempio n. 1
0
        private static HttpResponseMessage Post(Dictionary <string, string> resource, Dictionary <string, string> head, dynamic requesParams)
        {
            if (resource == null)
            {
                return(null);
            }
            if (string.IsNullOrEmpty(resource["BaseUrl"]))
            {
                throw new ArgumentNullException("baseUrl not is null!");
            }
            string resourceUrl = resource["Value"];

            //    string requestJson = "{}";
            if (string.IsNullOrEmpty(resourceUrl))
            {
                throw new ArgumentNullException("resource not is null!");
            }
            HttpResponseMessage response = null;

            if (requesParams != null && requesParams is IDictionary)
            {
                resourceUrl += GetParamsUrl(requesParams);
            }
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(resource["BaseUrl"]);
                // Add an Accept header for JSON format.
                // 为JSON格式添加一个Accept报头
                //注意这里的格式哦,为 "username:password"
                //  mycache.Add(new Uri(url), "Basic", new NetworkCredential(username, password));
                //  myReq.Credentials = mycache;
                //client.DefaultRequestHeaders.Accept.Add(
                //    new MediaTypeWithQualityHeaderValue("application/json"));
                if (head != null)
                {
                    foreach (var key in head.Keys)
                    {
                        client.DefaultRequestHeaders.Add(key,
                                                         head[key]);
                    }
                }
                if (requesParams is IDictionary)
                {
                    var request = new { req = "1" };
                    response = HttpClientExtensions.PostAsJsonAsync(client, resourceUrl, request).Result;
                }
                else
                {
                    MediaTypeFormatter jsonFormatter = new JsonMediaTypeFormatter();

                    // Use the JSON formatter to create the content of the request body.
                    // 使用JSON格式化器创建请求体内容。
                    HttpContent content = new ObjectContent <string>(requesParams, jsonFormatter);
                    response = client.PostAsync(resourceUrl, content).Result;
                }
            }
            return(response);
        }
Esempio n. 2
0
        /// <summary>
        /// Sends a POST request for the specified path to post <see cref="IDictionary{String,Object}"/> content, as an asynchronous operation.
        /// </summary>
        /// <param name="relativePath">The path to the api.</param>
        /// <param name="data">The data to send.</param>
        /// <returns>A task object representing the asynchronous operation.</returns>
        /// <exception cref="ArgumentException">relativePath is not a valid relative URI.</exception>
        public async Task <CbClientResult <string> > HttpPostDictionaryAsync(string relativePath, IDictionary <string, object> data)
        {
            Uri path = this.EnsureRelativeUri(relativePath);
            HttpResponseMessage response = await HttpClientExtensions.PostAsJsonAsync(this.httpClient, path.ToString(), data);

            return(await this.TransformResponse(response, async (c) =>
            {
                return await c.ReadAsStringAsync();
            }));
        }
Esempio n. 3
0
        public async Task <HttpResponseMessage> PostAsJson(string path, string param, dynamic data)
        {
            // var response = "";
            // var js = JsonConvert.SerializeObject(data);
            HttpResponseMessage response = await HttpClientExtensions.PostAsJsonAsync(client, path + param, data).ConfigureAwait(false);

            // try
            // {
            //     // if (response.StatusCode == HttpStatusCode.OK)
            //     // {
            //     //     return response.Content.ReadAsAsync<SRClient>();
            //     // }
            //     return response;
            // }
            // catch (Exception e)
            // {
            //     Debug.WriteLine(e);
            //     MessageBox.Show("Error 123");
            // }

            return(response);
        }
Esempio n. 4
0
        private static async Task <dynamic> Request <T>(AllowedHttpVerbs method, string url, dynamic parameters)
        {
            if (string.IsNullOrWhiteSpace(_developerKey))
            {
                throw new NoDeveloperKeyException();
            }

            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri(_apiBaseUri);
                client.DefaultRequestHeaders.Add("X-BetaSeries-Key", _developerKey);
                client.DefaultRequestHeaders.Add("X-BetaSeries-Version", _apiVersion);

                //add usertoken
                if (_userToken != null)
                {
                    client.DefaultRequestHeaders.Add("Authorization", $"Bearer {_userToken}");
                }

                //request
                HttpResponseMessage result = null;
                switch (method)
                {
                case AllowedHttpVerbs.Delete:
                    result = await client.DeleteAsync($"{url}");

                    break;

                case AllowedHttpVerbs.Get:
                    result = await client.GetAsync($"{url}");

                    break;

                case AllowedHttpVerbs.Post:
                    result = await HttpClientExtensions.PostAsJsonAsync(client, url, parameters);

                    break;

                case AllowedHttpVerbs.Put:
                    result = await HttpClientExtensions.PutAsJsonAsync(client, url, parameters);

                    break;
                }

                using (result)
                {
                    string resultAsString = await result.Content.ReadAsStringAsync();

                    if (result.IsSuccessStatusCode)
                    {
                        return(JsonConvert.DeserializeObject(resultAsString));
                    }
                    else
                    {
                        ErrorResponse errorResponse = JsonConvert.DeserializeObject <ErrorResponse>(resultAsString);

                        if (errorResponse != null)
                        {
                            throw new BetaSeriesException(errorResponse);
                        }

                        return(errorResponse);
                    }
                }
            }
        }