Example #1
0
        public static async Task <string> sendDataToServer(string aUrl, string json)
        {
            string result     = "";
            var    httpClient = new HttpClient();

            // Always catch network exceptions for async methods
            try
            {
                httpClient = new Windows.Web.Http.HttpClient();
                Windows.Web.Http.HttpRequestMessage msg = new Windows.Web.Http.HttpRequestMessage(new Windows.Web.Http.HttpMethod("POST"), new Uri(aUrl));
                msg.Content = new HttpStringContent((json));
                msg.Content.Headers.ContentType = new HttpMediaTypeHeaderValue("application/json");

                var response = await httpClient.SendRequestAsync(msg).AsTask();

                var statusCode = response.StatusCode;

                if (statusCode == HttpStatusCode.Ok)
                {
                    result = await response.Content.ReadAsStringAsync();
                }
            }
            catch
            {
                // Details in ex.Message and ex.HResult.
            }

            // Once your app is done using the HttpClient object call dispose to
            // free up system resources (the underlying socket and memory used for the object)
            httpClient.Dispose();

            return(result);
        }
Example #2
0
        protected override void Dispose(bool disposing)
        {
            if (disposing && !_disposed)
            {
                _client.Dispose();

                _disposed = true;
            }

            base.Dispose(disposing);
        }
Example #3
0
            public async Task <SystemNetHttpRequestResult> SendRequestAsync(string url, HttpMethod method, string contentType, string requestBody, byte[] requestBytes, Dictionary <string, string> headers, NetworkCredential credentials)
            {
                var filter = new HttpBaseProtocolFilter
                {
                    AutomaticDecompression = true,
                    AllowAutoRedirect      = true,
                    AllowUI = false
                };

                if (filter.IgnorableServerCertificateErrors != null)
                {
                    filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
                    filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName);
                }

                // use this to make sure we don't have weird behavior where the app caches credentials for way too long
                // the real fix seems to be using a new API introduced in 14295 but that's not the version that is targeted today
                // see: http://stackoverflow.com/questions/30731424/how-to-stop-credential-caching-on-windows-web-http-httpclient
                filter.CookieUsageBehavior = HttpCookieUsageBehavior.NoCookies;

                if (credentials != null)
                {
                    filter.ServerCredential = new PasswordCredential("2Day", credentials.UserName, credentials.Password);
                }
                else
                {
                    filter.ServerCredential = null;
                }

                var client = new HttpClient(filter);

                if (headers != null)
                {
                    foreach (var header in headers)
                    {
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                    }
                }

                var request = new Windows.Web.Http.HttpRequestMessage(method.ToWindowsHttp(), SafeUri.Get(url));
                HttpRequestMessage systemNetRequest = request.ToSystemHttp();

                if (requestBody != null)
                {
                    if (method != HttpMethod.Post)
                    {
                        throw new NotSupportedException("Request body must use POST method");
                    }

                    var arrayContent = new HttpBufferContent(requestBytes.AsBuffer());

                    if (!string.IsNullOrWhiteSpace(contentType))
                    {
                        arrayContent.Headers.ContentType = new HttpMediaTypeHeaderValue(contentType);
                    }

                    if (method == HttpMethod.Post)
                    {
                        request.Content = arrayContent;
                    }
                }

                WebRequestBuilder.TraceRequest(systemNetRequest, requestBody);
                CancellationTokenSource timeoutCancellationToken = new CancellationTokenSource(TimeSpan.FromSeconds(30));

                Windows.Web.Http.HttpResponseMessage response = await client.SendRequestAsync(request).AsTask(timeoutCancellationToken.Token);

                client.Dispose();

                HttpResponseMessage systemNetResponse = await response.ToWindowsHttp(systemNetRequest);

                return(new SystemNetHttpRequestResult
                {
                    Request = systemNetRequest,
                    Response = systemNetResponse
                });
            }
Example #4
0
 public void Dispose()
 {
     _httpClient?.Dispose();
 }
Example #5
0
        //prepared private
        public static async Task <string> CookiedGetUrl(string url, string referrer)
        {
            HttpResponseMessage response = null;

            try
            {
                HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Get, new Uri(url));
                req.Headers.Referer = new Uri(referrer);
                response            = await client.SendRequestAsync(req);

                req.Dispose();
            }
            catch (COMException e)
            {
                if ((uint)e.HResult == 0x80072f76)
                {
                    await ShowMessageDialog("可能是被验证码阻挡。",
                                            "错误代码:" + String.Format("{0:x8}", e.HResult) + "\n错误类型:" + e.GetType() + "\n错误信息:" +
                                            e.Message + "\n"
                                            + "如果是验证码问题,请不要立即点确定。请先打开浏览器,输入验证码。");

                    await ShowMessageDialog("提示", "如果已经输入验证码,可以确认继续;\n如果发现Cookie已失效,继续并稍后以重新设置Cookie");
                }
                try
                {
                    HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Get, new Uri(url));
                    req.Headers.Referer = new Uri(referrer);
                    response            = await client.SendRequestAsync(req);

                    req.Dispose();
                }
                catch (COMException e2)
                {
                    if ((uint)e2.HResult == 0x80072f76)
                    {
                        await ShowMessageDialog("错误未解决。",
                                                "错误类型:" + e2.GetType() + "\n错误信息:" + e2.Message + "\n持续网络故障。为避免故障扩大,程序将结束。可检查网络/jingyan.baidu.com,稍后再启动。");

                        Application.Current.Exit();
                    }
                    if ((uint)e2.HResult == 0x80072efd)
                    {
                        await ShowMessageDialog("错误未解决。80072efd,系统网络故障",
                                                "错误类型:" + e2.GetType() + "\n错误信息:" + e2.Message + "\n请百度80072efd寻找解决办法。该故障和系统网络设置有关。可能是被国产安全软件乱优化造成。\n持续网络故障。为避免故障扩大,程序将结束。可检查网络,稍后再启动。");

                        Application.Current.Exit();
                    }
                    client.Dispose();
                    await ShowMessageDialog("未知故障。可能是网络问题", "错误类型:" + e2.GetType() + "\n错误信息:" + e2.Message);

                    throw new COMException(e2.Message);
                }
            }

            if (response == null)
            {
                return("RESPONSE NULL");
            }

            if (response.StatusCode != HttpStatusCode.Ok)
            {
                return(response.StatusCode.ToString());
            }
            IHttpContent icont   = response.Content;
            IInputStream istream = await icont.ReadAsInputStreamAsync();

            StreamReader reader  = new StreamReader(istream.AsStreamForRead(), Encoding.UTF8);
            string       content = reader.ReadToEnd();

            reader.Dispose();
            istream.Dispose();
            icont.Dispose();
            response.Dispose();

            return(content);
        }
        protected async void postRequest()
        {
            string jsonInput = JsonConvert.SerializeObject(input);

            LogManager.WriteLine("jsonInput: " + jsonInput);
            HttpResponseMessage responseMessage = new HttpResponseMessage();

            CancellationTokenSource postTimeout = new CancellationTokenSource(); // 50 seconds

            postTimeout.CancelAfter(RestConfig.SOCKET_TIMEOUT_MS);

            CancellationTokenSource readTimeout = new CancellationTokenSource(); // 2 seconds

            readTimeout.CancelAfter(RestConfig.CONNECTION_TIMEOUT_MS);

            // POST REQUEST
            string GamificationLoginEndpoint = AppSettingsManager.GetAppSettings().engineServerEndPoint + GamificationLogin;

            LogManager.WriteLine("Gamification Login EndPoint: " + GamificationLoginEndpoint);
            Uri        gamificationServerUri = new Uri(GamificationLoginEndpoint);
            HttpClient client = GetConfiguredHttpClient();

            Encoding latinISO = Encoding.GetEncoding(RestConfig.OUTPUT_STREAM_CHARSET);

            byte[] messageArray = latinISO.GetBytes(jsonInput);

            MemoryStream ms = new MemoryStream(messageArray);

            IInputStream inStream = ms.AsInputStream();

            var request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, gamificationServerUri);

            request.Content = new HttpStreamContent(inStream);
            ((HttpStreamContent)request.Content).Headers.ContentType = new HttpMediaTypeHeaderValue("application/json");

            LogManager.WriteLine("Request: " + request);

            try
            {
                responseMessage = await client.PostAsync(request.RequestUri, request.Content).AsTask(postTimeout.Token);

                // READ RESPONSE
                try
                {
                    IInputStream responseStream = await responseMessage.Content.ReadAsInputStreamAsync().AsTask(readTimeout.Token);

                    string responseContent;
                    using (Stream receiveStream = responseStream.AsStreamForRead())
                    {
                        Encoding utf8 = Encoding.GetEncoding(RestConfig.INPUT_STREAM_CHARSET);
                        using (StreamReader readStream = new StreamReader(receiveStream, utf8))
                        {
                            responseContent = readStream.ReadToEnd();
                        }
                    }

                    string response = responseContent;

                    LogManager.WriteLine("response: " + response);

                    handleResponse(response);
                }

                catch (Exception e)
                {
                    WebErrorStatus status = WebError.GetStatus(e.HResult);

                    LogManager.WriteLine("Exception on Read Request: " + e);
                    handleResponse(e.Message);
                }
            }

            catch (Exception e)
            {
                WebErrorStatus status = WebError.GetStatus(e.HResult);

                LogManager.WriteLine("Error: " + status);

                LogManager.WriteLine("Exception on Post Request: " + e);
                handleResponse(e.Message);
            }

            // Once your app is done using the HttpClient object, we call 'Dispose' to
            // free up system resources (the underlying socket and memory used for the object)
            client.Dispose();
        }