public async Task<IEnumerable<ExternalLoginViewModel>> GetExternalLoginProviders()
		{
			string uri = String.Format("{0}/api/Account/ExternalLogins?returnUrl=%2F&generateState=true", _baseUri);
			HttpWebRequest request = new HttpWebRequest(new Uri(uri));
			request.Method = "GET";
			try
			{
				WebResponse response = await request.GetResponseAsync();
				HttpWebResponse httpResponse = (HttpWebResponse) response;
				string result;

				using (Stream responseStream = httpResponse.GetResponseStream())
				{
					result = new StreamReader(responseStream).ReadToEnd();
				}

				List<ExternalLoginViewModel> models = JsonConvert.DeserializeObject<List<ExternalLoginViewModel>>(result);
				return models;
			}
			catch (SecurityException)
			{
				throw;
			}
			catch (Exception ex)
			{
				throw new InvalidOperationException("Unable to get login providers", ex);
			}
		}
        public async Task<string> Login(string username, string password)
        {
            HttpWebRequest request = new HttpWebRequest(new Uri(String.Format("{0}Token", Constants.BaseAddress)));
            request.Method = "POST";

            string postString = String.Format("username={0}&password={1}&grant_type=password", HttpUtility.HtmlEncode(username), HttpUtility.HtmlEncode(password));
            byte[] bytes = Encoding.UTF8.GetBytes(postString);
            using (Stream requestStream = await request.GetRequestStreamAsync())
            {
                requestStream.Write(bytes, 0, bytes.Length);
            }

            try
            {
                HttpWebResponse httpResponse =  (HttpWebResponse)(await request.GetResponseAsync());
                string json;
                using (Stream responseStream = httpResponse.GetResponseStream())
                {
                    json = new StreamReader(responseStream).ReadToEnd();
                }
                TokenResponseModel tokenResponse = JsonConvert.DeserializeObject<TokenResponseModel>(json);
                return tokenResponse.AccessToken;
            }
            catch (Exception ex)
            {
                throw new SecurityException("Bad credentials", ex);
            }
        }
示例#3
0
        public static async Task <string> GetContainerSupplier(string containerId)
        {
            string supplier = string.Empty;
            string url      = String.Format(API + "{0}/containerSupplier", containerId);

            System.Net.HttpWebRequest requestForJason = (HttpWebRequest)WebRequest.Create(url);
            requestForJason.Method = "GET"; //make an HTTP POST
                                            //  var jsonstring = WebUtility.UrlEncode(JsonConvert.SerializeObject(vehiclebookingdata));// "{\"CarId\":\"\",\"DriverId\":null,\"EmployeeId\":null,\"EmployeeContactNumber\":null,\"EmployeeAddress\":\"Kothrud\",\"EmployeeName\":\"Kunal Kalbande\",\"Status\":\"cancelled\",\"BookingTime\":\"0001-01-01 00:00:00.000 +00:00\",\"Latitude\":18.4994,\"Longitude\":73.8279,\"DriverIds\":[\"adas\",\"asd\"],\"CarType\":\"mini\"}";
            requestForJason.ContentType = "application/json";
            // requestForJason.Accept = "application/json";
            Encoding encoding       = new UTF8Encoding();
            string   resultResponce = "";

            HttpWebResponse responseLocationMapping = await requestForJason.GetResponseAsync() as HttpWebResponse;

            if (responseLocationMapping != null)
            {
                //string Charset = response.;
                string Charset = "utf-8";
                encoding = Encoding.GetEncoding(Charset);
                var streamReaderResult = new StreamReader(responseLocationMapping.GetResponseStream(), encoding);
                resultResponce = streamReaderResult.ReadToEnd();
                streamReaderResult.Dispose();
                supplier = JsonConvert.DeserializeObject <string>(resultResponce);
            }
            return(supplier);
        }
        public async Task<bool> Register(string username, string password, string confirmPassword)
        {
            RegisterModel model = new RegisterModel
            {
                ConfirmPassword = confirmPassword,
                Password = password,
                UserName = username
            };

            HttpWebRequest request = new HttpWebRequest(new Uri(String.Format("{0}api/Account/Register", Constants.BaseAddress)));
            request.Method = "POST";
            request.ContentType = "application/json";
            request.Accept = "application/json";
            string json = JsonConvert.SerializeObject(model);
            byte[] bytes = Encoding.UTF8.GetBytes(json);
            using(Stream stream = await request.GetRequestStreamAsync())
            {
                stream.Write(bytes, 0, bytes.Length);
            }

            try
            {
                await request.GetResponseAsync();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
示例#5
0
        private static async Task<string> readResponse(HttpWebRequest rq, string expectedContentType)
        {
            HttpWebResponse rsp;
            try
            {
                rsp = (HttpWebResponse)await rq.GetResponseAsync();
            }
            catch (WebException wex)
            {
                rsp = (HttpWebResponse)wex.Response;
            }

            if (rsp.StatusCode != HttpStatusCode.OK) Console.Error.WriteLine(rsp.StatusCode.ToString());

            string[] contentType = rsp.ContentType.Split(new string[1] { "; " }, StringSplitOptions.None);
            if (contentType[0] != expectedContentType) Console.Error.WriteLine("Received Content-Type '{0}', expected '{1}'", contentType[0], expectedContentType);

            using (var st = rsp.GetResponseStream())
                using (var tr = new StreamReader(st, Encoding.UTF8))
                {
                    string rspstr = await tr.ReadToEndAsync();
                    if (displayResponse)
                    {
                        Console.Out.WriteLineAsync(rspstr);
                    }
                    return rspstr;
                }
        }
        private static async Task<string> GetResponseStringFromRequest(HttpWebRequest request)
        {
            try
            {
                using (var response = await request.GetResponseAsync()
                                                .ConfigureAwait(false))
                {
                    return GetResponseString(response);
                }
            }
            catch (WebException e)
            {
                using (var response = e.Response.GetResponseStream())
                {
                    if (response == null)
                    {
                        throw;
                    }
                    JObject responseItem;
                    try
                    {
                        responseItem = JObject.Load(new JsonTextReader(new StreamReader(response)));
                    }
                    catch (Exception)
                    {
                        throw e;
                    }
                    ThrowIfIsException(responseItem);

                    throw;
                }
            }
        }
示例#7
0
 public async Task<JToken> ExecuteRequestAsync(HttpWebRequest request)
 {
     EnforceRateLimit();
     var response = await request.GetResponseAsync();
     var result = await GetResponseStringAsync(response.GetResponseStream());
     return ExecuteRequestBase(result);
 }
示例#8
0
        public async Task<WebSocket> ConnectAsync(HttpWebRequest request, CancellationToken cancellationToken) {
            HttpWebResponse response;

            using (cancellationToken.Register(request.Abort)) {
                response = (HttpWebResponse)await request.GetResponseAsync();
            }

            InspectResponse?.Invoke(response);

            // TODO: Validate handshake
            HttpStatusCode statusCode = response.StatusCode;
            if (statusCode != HttpStatusCode.SwitchingProtocols) {
                response.Dispose();
                throw new InvalidOperationException("Incomplete handshake, invalid status code: " + statusCode);
            }
            // TODO: Validate Sec-WebSocket-Key/Sec-WebSocket-Accept

            string subProtocol = response.Headers[Constants.Headers.SecWebSocketProtocol];
            if (!string.IsNullOrEmpty(subProtocol) && !SubProtocols.Contains(subProtocol, StringComparer.OrdinalIgnoreCase)) {
                throw new InvalidOperationException("Incomplete handshake, the server specified an unknown sub-protocol: " + subProtocol);
            }

            var stream = response.GetResponseStream();

            return CommonWebSocket.CreateClientWebSocket(stream, subProtocol, KeepAliveInterval, ReceiveBufferSize, UseZeroMask);
        }
示例#9
0
        public async Task <string> SendDiscordOAuthRequestViaAuthCode(string code)
        {
            string authstring = $"https://discordapp.com/api/oauth2/token";

            Web webReq = (Web)WebRequest.Create(authstring);

            webReq.Method = "POST";
            string parameters = $"client_id={_id}&client_secret={_secret}&grant_type=authorization_code&code={code}&redirect_uri={_redirectURL}";

            byte[] byteArray = Encoding.UTF8.GetBytes(parameters);
            webReq.ContentType   = "application/x-www-form-urlencoded";
            webReq.ContentLength = byteArray.Length;
            Stream postStream = await webReq.GetRequestStreamAsync();

            await postStream.WriteAsync(byteArray, 0, byteArray.Length);

            postStream.Close();
            WebResponse response = await webReq.GetResponseAsync();

            postStream = response.GetResponseStream();
            StreamReader reader     = new StreamReader(postStream);
            string       responseFS = await reader.ReadToEndAsync();

            string tokenInfo    = responseFS.Split(',')[0].Split(':')[1];
            string access_token = tokenInfo.Trim().Substring(1, tokenInfo.Length - 3);

            return(access_token);
        }
        /// <summary>
        /// Queues a web request into our queue and returns an awaitable task.
        /// </summary>
        public static Task<XDocument> SendAsync(HttpWebRequest request)
        {
            lock (instance)
            {
                instance.currentTask = instance.currentTask.ContinueWith(async previousTask =>
                    {
                        var response = await request.GetResponseAsync();
                        var responseStream = response.GetResponseStream();

                        XDocument doc = null;
                        using (var streamReader = new StreamReader(responseStream))
                        {
                            string xml = await streamReader.ReadToEndAsync();
                            doc = XDocument.Parse(xml);
                        }

                        // Wait a bit to throttle the requests:
                        await Task.Delay(50);
                        return doc;

                    }).Unwrap();

                return instance.currentTask;
            }
        }
示例#11
0
 private static async Task<RESTResponse> ProcessResponse(HttpWebRequest request)
 {
     RESTResponse result = new RESTResponse();
     try
     {
         using (HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse)
         {
             result.StatusCode = (int)response.StatusCode;
             using (Stream stream = response.GetResponseStream())
             {
                 result.Content = new StreamReader(stream, System.Text.Encoding.UTF8).ReadToEnd();
             }
         }
     }
     catch (WebException ex)
     {
         if ((ex.Status == WebExceptionStatus.ProtocolError) && (ex.Response != null))
         {
             HttpWebResponse response = ex.Response as HttpWebResponse;
             result.StatusCode = (int)response.StatusCode;
             using (Stream stream = response.GetResponseStream())
             {
                 result.Content = new StreamReader(stream, System.Text.Encoding.UTF8).ReadToEnd();
             }
         }
     }
     return result;
 }
示例#12
0
        private async Task <JsonValue> GetUserCredentials(string url)
        {
            System.Net.HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
            request.ContentType = "application/json";
            request.Method      = "GET";

            using  (WebResponse response = await request.GetResponseAsync())
            {
                using (System.IO.Stream stream = response.GetResponseStream())
                {
                    try
                    {
                        JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));

                        Console.Out.WriteLine("Response: {0}, ", jsonDoc.ToString());

                        return(jsonDoc);
                    }
                    catch (System.Exception ex)
                    {
                        Console.Out.WriteLine(ex.StackTrace);
                        return(null);
                    }
                }
            }
            // return null;
        }
示例#13
0
        /// <summary>
        /// Gets GetResponseAsync implementation of the underlying HttpWebRequest class
        /// converted to the IHttpResponse interface.
        /// </summary>
        public Task <IHttpResponse> GetResponseAsync()
        {
            var tcs = new TaskCompletionSource <IHttpResponse>();

            request.GetResponseAsync().ContinueWith(responseTask =>
            {
                if (responseTask.IsFaulted)
                {
                    if (responseTask.Exception != null)
                    {
                        tcs.SetException(responseTask.Exception.InnerExceptions);
                    }
                }
                else if (responseTask.IsCanceled)
                {
                    tcs.SetCanceled();
                }
                else
                {
                    var response = responseTask.Result;
                    tcs.SetResult(new HttpWebResponse((System.Net.HttpWebResponse)response));
                }
            });
            return(tcs.Task);
        }
        /// <summary>
        /// GET请求
        /// </summary>
        /// <param name="url" "传入的url地址"></param>
        /// <returns></returns>
        public async Task GetStringAsync(string url)
        {
            string info = string.Empty;
            req = WebRequest.CreateHttp(url);
            req.Method = "GET";
            WebResponse res = null;
            req.ContinueTimeout = 1000;
            try
            {
                res = await req.GetResponseAsync();
               
            }
            catch (Exception e)
            {
                OnGetDataEvent(new ProgressEventArgs
                {
                    DownLoadData = null,
                    ExceptionInfo = e.Message,
                    IsComplete = false,
                    IsException = true
                });
                return;
            }
            
            //如果返回数据
            if (req.HaveResponse && null != res)
            {
                using (Stream stream = res.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        info = await reader.ReadToEndAsync();
                    }
                }
                //通知注册的事件完成下载
                OnGetDataEvent(new ProgressEventArgs
                {
                    DownLoadData = info,
                    ExceptionInfo = null,
                    IsComplete = true,
                    IsException = false
                });
            }
            else
            {
                //没有数据
                OnGetDataEvent(new ProgressEventArgs
                {
                    DownLoadData = null,
                    ExceptionInfo = null,
                    IsComplete = false,
                    IsException = true
                });
                return;
            }


        }
示例#15
0
 public async Task <IHttpWebResponse> GetResponseAsync(CancellationToken token)
 {
     try
     {
         using (token.Register(delegate
         {
             request.Abort();
         }, false))
         {
             Task <WebResponse>         requestTask     = request.GetResponseAsync();
             System.Net.HttpWebResponse httpWebResponse = (System.Net.HttpWebResponse)(await requestTask.ConfigureAwait(false));
             if (token.IsCancellationRequested)
             {
                 requestTask.ContinueWith(delegate(Task <WebResponse> task)
                 {
                     _ = task.Exception;
                 });
                 return(new HttpWebResponse
                 {
                     ErrorCode = ErrorCode.RequestTimedOut
                 });
             }
             if (httpWebResponse == null)
             {
                 return(new HttpWebResponse
                 {
                     ErrorCode = ErrorCode.NullResponse
                 });
             }
             return(new HttpWebResponse
             {
                 ErrorCode = ErrorCode.NoError,
                 Response = httpWebResponse,
                 Headers = httpWebResponse.Headers
             });
         }
     }
     catch (Exception ex)
     {
         WebException ex2 = (!(ex is AggregateException)) ? (ex as WebException) : (ex.InnerException as WebException);
         if (ex2 == null)
         {
             throw;
         }
         HttpStatusCode statusCode = HttpStatusCode.Unused;
         if (ex2.Status == WebExceptionStatus.ProtocolError)
         {
             statusCode = (ex2.Response as System.Net.HttpWebResponse).StatusCode;
         }
         return(new HttpWebResponse
         {
             ErrorCode = ErrorCode.WebExceptionThrown,
             ExceptionCode = ex2.Status,
             StatusCode = statusCode
         });
     }
 }
        public Task<WebResponse> GetResponseAsync(HttpWebRequest request, int timeoutMs)
        {
            if (timeoutMs > 0)
            {
                return GetResponseAsync(request, TimeSpan.FromMilliseconds(timeoutMs));
            }

            return request.GetResponseAsync();
        }
示例#17
0
        private async Task GetRequestStreamCallback(Task<Stream> task, HttpWebRequest request)
        {
            Stream postStream = await task.ConfigureAwait(false);

            this.WriteMultipartObject(postStream, this.Parameters);
            postStream.Close();

            var responseTask = request.GetResponseAsync();
            await GetResponseCallback(responseTask);
        }
示例#18
0
 static HttpWebResponse CreateResponse(HttpWebRequest request)
 {
     HttpWebResponse response = null;
     try
     {
         response = (HttpWebResponse)(request.GetResponseAsync().Result);
     }
     catch { }
     return response;
 }
示例#19
0
        public Task<WebResponse> GetDownloadStreamAsync()
        {
            request = (HttpWebRequest)WebRequest.Create(
                "http://www.nicovideo.jp/api/watch/mylistvideo?id=" + id);

            request.Method = ContentMethod.Get;
            request.CookieContainer = cookieContainer;

            return request.GetResponseAsync();
        }
示例#20
0
        public Task<WebResponse> GetDownloadStreamAsync()
        {
            request = (HttpWebRequest)WebRequest.Create(
                "http://ext.nicovideo.jp/api/getthumbinfo/" + id);

            request.Method = ContentMethod.Get;
            request.CookieContainer = cookieContainer;

            return request.GetResponseAsync();
        }
示例#21
0
 private async Task<string> _getApiResponseAsync(HttpWebRequest request)
 {
     using (var response = await request.GetResponseAsync())
     {
         using (var streamReader = new StreamReader(response.GetResponseStream()))
         {
             return streamReader.ReadToEnd();
         }
     }
 }
示例#22
0
        public Task<WebResponse> GetDownloadStreamAsync()
        {
            request = (HttpWebRequest)WebRequest.Create(
                "http://flapi.nicovideo.jp/api/getpostkey/?yugi=&version_sub=2&device=1&block_no="
                + block_no
                + "&version=1&thread=" + thread);

            request.Method = ContentMethod.Get;
            request.CookieContainer = cookieContainer;

            return request.GetResponseAsync();
        }
示例#23
0
        /**
         * Async GET
         * **/
        public async Task <string> GetAsync(string uri)
        {
            System.Net.HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
            request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

            using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
                using (Stream stream = response.GetResponseStream())
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        return(await reader.ReadToEndAsync());
                    }
        }
示例#24
0
        public static async Task <Tuple <string, int, bool> > GetAsync(string uri, int i, bool type)
        {
            System.Net.HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri + i);
            request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

            using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
                using (Stream stream = response.GetResponseStream())
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        return(new Tuple <string, int, bool>(await reader.ReadToEndAsync(), i, type));
                    }
        }
示例#25
0
        public async Task <bool> ExecuteAsync()
        {
            try
            {
                this.Watch = System.Diagnostics.Stopwatch.StartNew();
                System.Net.HttpWebRequest webrequest = (HttpWebRequest)System.Net.WebRequest.Create(this.Url);
                webrequest.Method      = this.Method;
                webrequest.ContentType = this.ContentType;
                webrequest.Timeout     = this.TimeoutMilliseconds;
                if (this.Certificate != null)
                {
                    webrequest.ServerCertificateValidationCallback = (message, cert, chain, errors) => true;
                    webrequest.ClientCertificates.Add(this.Certificate);
                }

                switch (this.Method)
                {
                case "PUT":
                case "POST":
                    var byteArray = Encoding.UTF8.GetBytes(this.PayLoad);
                    webrequest.ContentLength = byteArray.Length;
                    await(await webrequest.GetRequestStreamAsync()).WriteAsync(byteArray, 0, byteArray.Length);
                    break;

                case "GET":
                default:
                    webrequest.ContentLength = 0;
                    break;
                }

                this.Request = $"{Url} {PayLoad}";

                using (var response = await webrequest.GetResponseAsync())
                {
                    var responseStream = response.GetResponseStream();
                    this.Watch.Stop();
                    this.ElapsedTime = (int)Watch.ElapsedMilliseconds;
                    this.Response    = await(new StreamReader(response.GetResponseStream())).ReadToEndAsync();
                }
                return(true);
            }
            catch (Exception e)
            {
                this.Watch.Stop();
                this.ElapsedTime = (int)Watch.ElapsedMilliseconds;
                if (e.GetType() == typeof(WebException) && ((WebException)e).Response != null)
                {
                    this.Response = await(new StreamReader(((WebException)e).Response.GetResponseStream())).ReadToEndAsync();
                }

                throw;
            }
        }
示例#26
0
        //测试方法
        public static async Task <string> PostTest(string url, string jsonParas)
        {
            string          str      = string.Empty;
            HttpWebResponse response = null;

            try
            {
                byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(jsonParas);                  //将数据转换成对应的网站编码
                System.Net.HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(url); //发出请求
                                                                                                   //ServicePointManager.DefaultConnectionLimit = 100;
                webRequest.ContentType = "application/Json";                                       //报表头类型
                webRequest.Method      = "POST";                                                   //请求方式Post
                                                                                                   // webRequest.Timeout = 12000;//请求的超时时间
                                                                                                   // webRequest.ContentLength = byteArray.Length;//获取要传输的长度
                Stream requeststream = await webRequest.GetRequestStreamAsync();                   //获取写入的数据流

                //StreamWriter strw = new StreamWriter(requeststream);
                requeststream.Write(byteArray, 0, byteArray.Length);//将数据写入到当前流中

                try
                {
                    response = (HttpWebResponse)(await webRequest.GetResponseAsync());//获得响应流
                }
                catch (WebException ex) { response = (HttpWebResponse)ex.Response; }
                if (response == null)
                {
                    throw new Exception("");
                }

                using (var stream2 = response.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(stream2, Encoding.UTF8);
                    string       text   = reader.ReadToEnd();
                    if (text.StartsWith("{"))
                    {
                        return(text);
                    }
                    throw new Exception("返回Json数据失败\r\n" + text);
                }
            }
            finally
            {
                if (response != null)
                {
                    response.Dispose();
                }
            }
        }
        public static async Task <HttpWebResponse> UpdateRequestAsync <TModel>(TModel model, string url)
        {
            System.Net.HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method      = "PUT";
            request.ContentType = "application/json";
            //JavaScriptSerializer serializer = new JavaScriptSerializer();
            using (var sw = new StreamWriter(request.GetRequestStream()))
            {
                string json = JsonConvert.SerializeObject(model);
                sw.Write(json);
                sw.Flush();
            }
            HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync();

            return(response);
        }
示例#28
0
        public async Task <DiscordUser> GetDiscordUser(string id)
        {
            Web webReq = (Web)WebRequest.Create("https://discordapp.com/api/v6/users/" + id);

            webReq.Method        = "Get";
            webReq.ContentLength = 0;
            webReq.Headers.Add("Authorization", "Bot " + _token);
            webReq.ContentType = "application/x-www-form-urlencoded";
            var response1 = await webReq.GetResponseAsync();

            StreamReader reader1      = new StreamReader(((HttpWebResponse)response1).GetResponseStream());
            string       apiResponse1 = await reader1.ReadToEndAsync();

            DiscordUser user = JsonConvert.DeserializeObject <DiscordUser>(apiResponse1);

            return(user);
        }
示例#29
0
        protected async Task<string> GetResponseAsync(HttpWebRequest request)
        {
            string result = string.Empty;
            try
            {
                var response = (HttpWebResponse)(await request.GetResponseAsync());

                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    result = await reader.ReadToEndAsync();
                }
            }
            catch (WebException ex)
            {
                result = GetExcepcionResponse(ex);
            }
            return result;
        }
		public async Task RegisterExternal(
			string username)
		{
			string uri = String.Format("{0}/api/Account/RegisterExternal", BaseUri);

			RegisterExternalBindingModel model = new RegisterExternalBindingModel
			{
				UserName = username
			};
			HttpWebRequest request = new HttpWebRequest(new Uri(uri));

			request.ContentType = "application/json";
			request.Accept = "application/json";
			request.Headers.Add("Authorization", String.Format("Bearer {0}", AccessToken));
			request.Method = "POST";

			string postJson = JsonConvert.SerializeObject(model);
			byte[] bytes = Encoding.UTF8.GetBytes(postJson);
			using (Stream requestStream = await request.GetRequestStreamAsync())
			{
				requestStream.Write(bytes, 0, bytes.Length);
			}

			try
			{
				WebResponse response = await request.GetResponseAsync();
				HttpWebResponse httpResponse = (HttpWebResponse)response;
				string result;

				using (Stream responseStream = httpResponse.GetResponseStream())
				{
					result = new StreamReader(responseStream).ReadToEnd();
					Console.WriteLine(result);
				}
			}
			catch (SecurityException)
			{
				throw;
			}
			catch (Exception ex)
			{
				throw new InvalidOperationException("Unable to register user", ex);
			}
		}
示例#31
0
        /// <summary>
        /// Main download method.
        /// </summary>
        private async void download()
        {
            dlTimer.Start();
            dsTimer.Start();
            // Set 'cancelDownload' to false, so that method can stop again.
            cancelDownload = false;

            req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri);
            // check if downloaded-length!=0 and !overwrite so the user want to resume.
            if (dLength > 0 && !overwrite)
            {
                req.AddRange(dLength);      // add range to the 'req' to change the point of start download.
            }
            isDownloading = true;
            using (res = (System.Net.HttpWebResponse) await req.GetResponseAsync())
            {
                fLength = res.ContentLength + dLength;                                               // get the total-size of the file.
                eSize.Invoke(null, View.Size.getlength.GetLengthString(FileSize));                   // update the total-size.
                eDownloadedSize.Invoke(null, View.Size.getlength.GetLengthString(DownloadedLength)); // update the downloaded-length.
                dt = System.DateTime.Now;                                                            // get the current time ( point of start downloading ).
                using (stream = res.GetResponseStream())
                {
                    await System.Threading.Tasks.Task.Run(() =>     // await task so the winform don't freezing.
                    {
                        // update the download-state.
                        eDownloadState.Invoke(null, "Downloading");
                        // while not 'cancelDownload' and file doesn't end do:
                        while (!cancelDownload && ((bufferReader = stream.Read(buffer, 0, buffer.Length)) > 0))
                        {
                            fStream.Write(buffer, 0, bufferReader); // write byte to the file on harddisk.
                            dLength += bufferReader;                // update downloaded-length value.
                            cLength += bufferReader;                // update current-downloaded-length value.
                        }
                    });
                }
            }
            dlTimer.Stop();
            dsTimer.Stop();
            isDownloading = false;
            // eSpeed.Invoke(null, "0.0 Kb/s");    // update downloading-speed to 0.0 kb/s.
            eDownloadedSize.Invoke(null, View.Size.getlength.GetLengthString(DownloadedLength)); // update downloaded-size.
            eDownloadState.Invoke(null, DownloadState);                                          // update download-state.
            fStream.Dispose();                                                                   // free file on harddisk by dispose 'fStream'.
        }
示例#32
0
        public async Task <Client> RequestPostAsync(string data_string)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(data_string);

            foreach
            (
                KeyValuePair <Uri, ClientRequestImplementation <ImplementationRequest> > kvp
                in this.RequestImplementationObjects
            )
            {
                Uri uri = kvp.Key;
                ImplementationRequest request = kvp.Value.ImplementationObject;

                RequestSetup(request);

                #if NETSTANDARD1_0
                using (Stream stream = await request.GetRequestStreamAsync())
                {
                    await stream.WriteAsync(bytes, 0, bytes.Length);

                    await stream.FlushAsync();
                }

                ImplementationResponse response = (ImplementationResponse)await request.GetResponseAsync();

                this.ResponseImplementationObjects.Add(uri, response);
                #else
                request.Content =
                    new System.Net.Http.StringContent(data_string)
                    //new System.Net.Http.ByteArrayContent(new byte[]{})
                ;

                using (System.Net.Http.HttpClient http_client = new System.Net.Http.HttpClient())
                {
                    ImplementationResponse response = await http_client.SendAsync(request);

                    this.ResponseImplementationObjects.Add(uri, response);
                }
                #endif
            }

            return(this);
        }
示例#33
0
        /// <summary>
        /// 上传的文件
        /// </summary>
        /// <param name="url">服务器请求地址</param>
        /// <param name="paramDate">发送的数据</param>
        /// <param name="encode">网站编码</param>
        /// <returns>字符串类型的true/false</returns>
        public static async Task <string> PostMoth(string url, string paramDate, System.Text.Encoding encode)
        {
            string str = string.Empty;

            try
            {
                byte[] byteArray = encode.GetBytes(paramDate);                                     //将数据转换成对应的网站编码
                System.Net.HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(url); //发出请求
                                                                                                   //ServicePointManager.DefaultConnectionLimit = 100;
                webRequest.ContentType = "application/x-www-form-urlencoded";                      //报表头类型
                webRequest.Method      = "POST";                                                   //请求方式Post
                                                                                                   // webRequest.Timeout = 12000;//请求的超时时间
                                                                                                   // webRequest.ContentLength = byteArray.Length;//获取要传输的长度
                Stream requeststream = await webRequest.GetRequestStreamAsync();                   //获取写入的数据流

                //StreamWriter strw = new StreamWriter(requeststream);
                requeststream.Write(byteArray, 0, byteArray.Length);                                  //将数据写入到当前流中
                HttpWebResponse webResponse = (HttpWebResponse)(await webRequest.GetResponseAsync()); //返回来自服务器的相应
                if (webResponse.StatusCode == HttpStatusCode.OK)
                {
                    if (webResponse.Headers["Content-Encoding"] != null && webResponse.Headers["Content-Encoding"].ToLower().Contains("gzip"))//如果http头中接受gzip的话,这里就要判断是否为有压缩,有的话,直接解压缩即可
                    {
                        requeststream = new System.IO.Compression.GZipStream(requeststream,
                                                                             System.IO.Compression.CompressionMode.Decompress); //解压缩基础流
                    }
                    StreamReader strReader = new StreamReader(webResponse.GetResponseStream());                                 //读取对应编码的文件流
                    str = strReader.ReadToEnd();                                                                                //读文件流至最后
                    webResponse.Dispose();
                    strReader.Dispose();
                    requeststream.Dispose();//关闭文件流
                    return("true");
                }
                else
                {
                    return("false");
                }
            }
            catch (Exception e)
            {
                return(e.ToString());
            }
        }
示例#34
0
 /// <summary>
 ///     Executes a web request using the given request, and returns the HttpWebResponse
 /// </summary>
 /// <param name="request">The web request</param>
 /// <returns></returns>
 public static async Task<HttpWebResponse> GetResponseAsync(HttpWebRequest request) {
     HttpWebResponse response;
     try {
         response = (HttpWebResponse) await request.GetResponseAsync().ConfigureAwait(false);
         if (response != null) {
             Trace.TraceEvent(TraceEventType.Information, 0,
                 "Response status: " + response.StatusCode + ", " + response.StatusDescription);
             Trace.TraceEvent(TraceEventType.Verbose, 0, "From cache: " + response.IsFromCache);
         }
     }
     catch (WebException e) {
         response = (HttpWebResponse) e.Response;
         if (response == null) throw;
         Trace.TraceEvent(TraceEventType.Information, 0,
             "Response status: " + response.StatusCode + ", " + response.StatusDescription);
         Trace.TraceEvent(TraceEventType.Verbose, 0, "From cache: " + response.IsFromCache);
         throw;
     }
     return response;
 }
        private async Task<SessionBookingData> getSessionBookingData(HttpWebRequest request)
        {
            SessionBookingData sessionBookingData = null;

            // Generating JSON Response and Converting it to Student Object.
            using (WebResponse response = await request.GetResponseAsync())
            {
                // Get a stream representation of the HTTP web response:
                using (Stream stream = response.GetResponseStream())
                {
                    using (StreamReader sr = new StreamReader(stream))
                    {
                        string json = sr.ReadToEnd();

                        // Convert JSON Response to Student Object
                        sessionBookingData = JsonConvert.DeserializeObject<SessionBookingData>(json);
                    }

                    try
                    {
                        if (sessionBookingData == null)
                        {
                            Log.Info("HELPS", "No bookings found");
                        }

                        else
                        {
                            Log.Info("HELPS:assignType", sessionBookingData.attributes.ToString());
                        }
                    }

                    catch (NullReferenceException ex)
                    {
                        Log.Info("HELPS", "Exception: No bookings found");
                        sessionBookingData = null;
                    }
                }
            }
            return sessionBookingData;
        }
示例#36
0
        protected string GetResponse(HttpWebRequest request)
        {
            string result = string.Empty;
            try
            {
                var response = (HttpWebResponse)(request.GetResponseAsync().Result);

                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    result = reader.ReadToEnd();
                }
            }
            catch (WebException ex)
            {
                HandleWebException(ex);
            }
            catch (AggregateException ex)
            {
                HandleWebException((WebException) ex.InnerException);
            }
            return result;
        }
示例#37
0
        protected async void OnClick(object sender, EventArgs e)
        {
            Uri WebUri = new Uri("https://api.worldbank.org/v2/en/country/all/indicator/NY.GDP.MKTP.CD?format=json&per_page=500&date=2017&MRNEV=1", UriKind.Absolute);

            System.Net.HttpWebRequest webrequest = (HttpWebRequest)System.Net.WebRequest.Create(WebUri);
            WebResponse webresponse = await webrequest.GetResponseAsync();

            StreamReader webstream = new StreamReader(webresponse.GetResponseStream(), Encoding.UTF8);
            string       json      = webstream.ReadToEnd();

            JsonConverter[] converters = { new GDPDATAConverter() };
            List <GDPDATA>  gdp        = JsonConvert.DeserializeObject <List <GDPDATA> >(json, new JsonSerializerSettings()
            {
                Converters = converters
            });

            GDPGridView.DataSource = gdp[1].Indicators.Where <Indicator>(x => x.Countryiso3Code.Length > 1).OrderBy(x => x.Value).Reverse <Indicator>().Take <Indicator>(Convert.ToInt32(txtTop.Text));


            GDPGridView.DataBind();
            // process the response
        }
示例#38
0
        public async Task<String> GetHttpPostResponse(HttpWebRequest request, string postData)
        {
            Received = null;
            request.Method = "POST";

            request.ContentType = "application/x-www-form-urlencoded";

            var requestBody = Encoding.UTF8.GetBytes(postData);

            // ASYNC: using awaitable wrapper to get request stream
            using (var postStream = await request.GetRequestStreamAsync())
            {
                // Write to the request stream.
                // ASYNC: writing to the POST stream can be slow
                await postStream.WriteAsync(requestBody, 0, requestBody.Length);
            }

            try
            {
                // ASYNC: using awaitable wrapper to get response
                var response = (HttpWebResponse) await request.GetResponseAsync();
                if (response != null)
                {
                    var reader = new StreamReader(response.GetResponseStream());
                    // ASYNC: using StreamReader's async method to read to end, in case
                    // the stream i slarge.
                    Received = await reader.ReadToEndAsync();
                }
            }
            catch (WebException we)
            {
                var reader = new StreamReader(we.Response.GetResponseStream());
                var responseString = reader.ReadToEnd();
                Debug.WriteLine(responseString);
                return responseString;
            }
            return Received;
        }
示例#39
0
        public static async Task <bool> UpdateApprovalStatus(string containerId, ApprovalsDetails request)
        {
            bool   result     = false;
            var    jsonstring = JsonConvert.SerializeObject(request);
            string url        = String.Format(API + "{0}/approvalStatus", containerId);

            System.Net.HttpWebRequest requestForJason = (HttpWebRequest)WebRequest.Create(url);
            requestForJason.Method = "POST"; //make an HTTP POST
                                             //  var jsonstring = WebUtility.UrlEncode(JsonConvert.SerializeObject(vehiclebookingdata));// "{\"CarId\":\"\",\"DriverId\":null,\"EmployeeId\":null,\"EmployeeContactNumber\":null,\"EmployeeAddress\":\"Kothrud\",\"EmployeeName\":\"Kunal Kalbande\",\"Status\":\"cancelled\",\"BookingTime\":\"0001-01-01 00:00:00.000 +00:00\",\"Latitude\":18.4994,\"Longitude\":73.8279,\"DriverIds\":[\"adas\",\"asd\"],\"CarType\":\"mini\"}";
            requestForJason.ContentType = "application/json";
            // requestForJason.Accept = "application/json";
            Encoding encoding = new UTF8Encoding();

            byte[] data = encoding.GetBytes(jsonstring);
            using (var stream = await requestForJason.GetRequestStreamAsync())
            {
                // var streamwriter = new StreamWriter(stream);
                //streamwriter.Write(postdata);
                // streamwriter.Flush();
                stream.Write(data, 0, data.Length);
                stream.Dispose();
            }
            string resultResponce = "";

            HttpWebResponse responseLocationMapping = await requestForJason.GetResponseAsync() as HttpWebResponse;

            if (responseLocationMapping != null)
            {
                result = true;
                //string Charset = response.;
                string Charset = "utf-8";
                encoding = Encoding.GetEncoding(Charset);
                var streamReaderResult = new StreamReader(responseLocationMapping.GetResponseStream(), encoding);
                resultResponce = streamReaderResult.ReadToEnd();
                streamReaderResult.Dispose();
            }
            return(result);
        }
示例#40
0
        private JsonValue FetchWeatherAsync(string url)
        {
            // Create an HTTP web request using the URL:
            System.Net.HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create((url));

            request.ContentType = "application/json";
            request.Method      = "GET";

            // Send the request to the server and wait for the response:
            using (WebResponse response = request.GetResponseAsync().Result)
            {
                // Get a stream representation of the HTTP web response:
                using (Stream stream = response.GetResponseStream())
                {
                    // Use this stream to build a JSON document object:
                    JsonValue jsonDoc = JsonObject.Load(stream);
                    //!! Console.Out.WriteLine("Response: {0}", jsonDoc.ToString());

                    // Return the JSON document:
                    return(jsonDoc);
                }
            }
        }
        public async Task<IEnumerable<string>> GetValues(string accessToken)
        {
            HttpWebRequest request = new HttpWebRequest(new Uri(String.Format("{0}api/Values", Constants.BaseAddress)));
            request.Method = "GET";
            request.Accept = "application/json";
            request.Headers.Add("Authorization", String.Format("Bearer {0}", accessToken));

            try
            {
                HttpWebResponse httpResponse = (HttpWebResponse)(await request.GetResponseAsync());
                string json;
                using (Stream responseStream = httpResponse.GetResponseStream())
                {
                    json = new StreamReader(responseStream).ReadToEnd();
                }
                List<string> values = JsonConvert.DeserializeObject<List<string>>(json);
                return values;
            }
            catch (Exception ex)
            {
                throw new SecurityException("Bad credentials", ex);
            }
        }
示例#42
0
        public Resources(GARSetup garSetup, Logger logger)
        {
            this.garSetup = garSetup;

            X509Certificate2 listeRessourcesCert = null;

            // the certificate MUST contains the RSA private key
            if (garSetup.listeRessourcesCert != null)
            {
                listeRessourcesCert = new X509Certificate2(Convert.FromBase64String(garSetup.listeRessourcesCert));
            }

            BeforeAsync = async(p, c) => await c.EnsureIsAuthenticatedAsync();

            GetAsync["/structures/{id}/resources"] = async(p, c) =>
            {
                XElement           doc     = null;
                Net.HttpWebRequest request = (Net.HttpWebRequest)Net.WebRequest.Create(garSetup.listeRessourcesUrl);
                request.PreAuthenticate   = true;
                request.AllowAutoRedirect = true;
                // if localhost, allow invalid certificate
                if (request.Host == "localhost")
                {
                    request.ServerCertificateValidationCallback = (obj, certificate, chain, errors) => true;
                }
                if (listeRessourcesCert != null)
                {
                    request.ClientCertificates.Add(listeRessourcesCert);
                }

                try
                {
                    using (var response = (Net.HttpWebResponse) await request.GetResponseAsync())
                    {
                        using (Stream dataStream = response.GetResponseStream())
                        {
                            doc = XElement.Load(dataStream);
                        }
                    }
                }
                catch (Net.WebException e)
                {
                    if (e.InnerException is System.Security.Authentication.AuthenticationException)
                    {
                        logger.Log(LogLevel.Error, "Authentication failed for GAR listeRessources API");
                    }
                    else
                    {
                        logger.Log(LogLevel.Error, "GAR listsRessouces API fails: " + e);
                    }
                }
                if (doc != null)
                {
                    // convert to JSON
                    var resources = new JsonArray();
                    foreach (XElement element in (from node in doc.Elements() where node.Name == "ressource" select node))
                    {
                        var resource = new JsonObject();
                        resources.Add(resource);
                        ConvertNodes(resource, element, "idRessource", "idType", "nomRessource",
                                     "idEditeur", "nomEditeur", "urlVignette", "urlAccesRessource",
                                     "nomSourceEtiquetteGar", "distributeurTech", "validateurTech");
                        ConvertMultiNodes(resource, element, "typePresentation", "typologieDocument",
                                          "niveauEducatif", "domaineEnseignement");
                    }
                    c.Response.StatusCode = 200;
                    c.Response.Content    = resources;
                }
            };
        }
示例#43
0
        private async Task<string> VerifyResponseBody(HttpWebRequest request)
        {
            HttpWebResponse response = null;
            try
            {
                response = (HttpWebResponse)(await request
                    .GetResponseAsync().ConfigureAwait(false));
            }
            catch (WebException e)
            {
                response = (HttpWebResponse)e.Response;
            }
            try
            {
                Cookies.SetCookies(request.RequestUri,
                    response.Headers["Set-Cookie"] ?? string.Empty);

                // contains(text/html)
                string body = string.Empty;
                using (Stream responseStream = response.GetResponseStream())
                using (var bodyStream = new StreamReader(responseStream))
                {
                    body = await bodyStream.ReadToEndAsync()
                       .ConfigureAwait(false);
                }

                if (body.Contains("setCookie('"))
                {
                    UpdateCookies(body, request);

                    body = await DownloadStringAsync(
                        request.RequestUri).ConfigureAwait(false);
                }
                return body;
            }
            finally { response?.Dispose(); }
        }
        /// <summary>
        /// Submits a web request and retrieves the returned data as a string
        /// </summary>
        /// <param name="request">Request to submit</param>
        /// <returns></returns>
        private async Task<string> AsyncWebAction( HttpWebRequest request )
        {
            // Send the request to the server and wait for the response
            using (WebResponse response = await request.GetResponseAsync())
            {
                // Get a stream representation of the HTTP web response
                using( System.IO.Stream stream = response.GetResponseStream() )
                {
                    // Get the returned string
                    StreamReader reader = new StreamReader( stream );
                    string returnString = await Task.Run( () => reader.ReadToEnd() );

                    // Return the string
                    return returnString;
                }
            }
        }
示例#45
0
        /// <summary>
        /// http or https get request
        /// </summary>
        /// <param name="requestInput"></param>
        /// <param name="remoteCertificateValidationCallback"></param>
        /// <returns></returns>
        public static async Task <string> RequestGetAsync(HttpRequestArgs requestInput, Func <object, X509Certificate, X509Chain, SslPolicyErrors, bool> remoteCertificateValidationCallback = null)
        {
            var res = string.Empty;

            try
            {
                System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(requestInput.Url);

                if (requestInput.TimeOut > 0)
                {
                    request.Timeout = requestInput.TimeOut;
                }

                foreach (var header in requestInput.Headers)
                {
                    request.Headers.Add(header.Key, header.Value);
                }

                //验证服务器证书回调自动验证
                ServicePointManager.ServerCertificateValidationCallback = ((remoteCertificateValidationCallback == null) ? new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult) : new System.Net.Security.RemoteCertificateValidationCallback(remoteCertificateValidationCallback));
                using (System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)(await request.GetResponseAsync()))
                {
                    Encoding coding = string.IsNullOrEmpty(requestInput.CharSet) ? System.Text.Encoding.UTF8 : System.Text.Encoding.GetEncoding(requestInput.CharSet);
                    using (System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream(), coding))
                    {
                        var responseMessage = reader.ReadToEnd();
                        if (response.StatusCode == HttpStatusCode.OK)
                        {
                            res = responseMessage;
                        }
                    }
                }

                request = null;
            }
            catch (Exception ex)
            {
                res = string.Format("ERROR:{0}", ex.Message);
            }
            return(res);
        }
示例#46
0
 internal static async Task<IAuthStatus> DoAuthRequestHandleResponseAsync(HttpWebRequest request)
 {
     WebResponse response = null;
     try
     {
         response = await request.GetResponseAsync();
     }
     catch (WebException webEx)
     {
         if ((webEx.Status == WebExceptionStatus.ConnectFailure) ||
             (webEx.Status == WebExceptionStatus.SendFailure) ||
             (webEx.Response == null || String.IsNullOrWhiteSpace(webEx.Response.ContentType)))
         {
             HockeyClient.Current.AsInternal().HandleInternalUnhandledException(webEx);
             throw new WebTransferException("Could not connect to server.", webEx);
         }
         else
         {
             if ((webEx.Response as HttpWebResponse).StatusCode == HttpStatusCode.NotFound)
             {
                 return AuthStatus.NotFoundAuthStatus;
             }
             else if ((webEx.Response as HttpWebResponse).StatusCode == HttpStatusCode.Unauthorized)
             {
                 return AuthStatus.NotAuthorizedAuthStatus;
             }
             //sent if token is invalid
             else if ((int)(webEx.Response as HttpWebResponse).StatusCode == 422)
             {
                 return AuthStatus.NotAuthorizedAuthStatus;
             }
             else
             {
                 HockeyClient.Current.AsInternal().HandleInternalUnhandledException(webEx);
                 return AuthStatus.InvalidAuthStatus;
             }
         }
     }
     IAuthStatus checkedAuthStatus = await TaskEx.Run(() => AuthStatus.FromJson(response.GetResponseStream()));
     return checkedAuthStatus;
 }
示例#47
0
        //查看成绩页面
        private async void btnGrade_Click(object sender, RoutedEventArgs e)
        {
            ProgressView.ProgressIndicator progress = new ProgressView.ProgressIndicator();
            progress.Text = "请等待";
            progress.Show();

            if (gd == null)
            {
                await new MessageDialog("登录有误,请重新登录!").ShowAsync();
                //ShowWaitingRing(false);
                progress.Hide();
                return;
            }
            HttpRequestMessage  request;
            HttpResponseMessage response;

            //    byte[] bytedata;
            try
            {
                HttpBaseProtocolFilter filter = gd.loginInfo.ob as HttpBaseProtocolFilter;
                if (filter == null)
                {
                    //ShowWaitingRing(false);
                    //IsWorking = false;
                    progress.Hide();
                    return;
                }

                HttpClient client = new HttpClient(filter);
                request = new HttpRequestMessage(HttpMethod.Get,
                                                 new Uri("http://gdjwgl.bjut.edu.cn/xscjcx.aspx?xh=" + gd.StudentID + "&xm=" + gd.StudentName + "&gnmkdm=N121605"));

                request.Headers["Referer"] = "http://gdjwgl.bjut.edu.cn/xs_main.aspx?xh=" + gd.StudentID;

                response = await client.SendRequestAsync(request, HttpCompletionOption.ResponseHeadersRead);


                string str = await response.Content.ReadAsStringAsync();

                //request.Dispose();
                //response.Dispose();

                string __VIEWSTATEString;
                __VIEWSTATEString = gd.GetVIEWSTATE(str);

                IDictionary <string, string> parameters = new Dictionary <string, string>();
                parameters.Add("__EVENTTARGET", "");
                parameters.Add("__EVENTARGUMENT", "");
                parameters.Add("__VIEWSTATE", SystemNet.WebUtility.UrlEncode(__VIEWSTATEString));
                parameters.Add("hidLanguage", "");
                parameters.Add("ddlXN", "");
                parameters.Add("ddlXQ", "");
                parameters.Add("ddl_kcxz", "");
                parameters.Add("btn_zcj", SystemNet.WebUtility.UrlEncode("历年成绩"));
                string buffer = "";

                int i = 0;
                foreach (string key in parameters.Keys)
                {
                    if (i > 0)
                    {
                        buffer += "&" + key + "=" + parameters[key];
                    }
                    else
                    {
                        buffer = key + "=" + parameters[key];
                    }
                    i++;
                }


                byte[] bytedata = Encoding.UTF8.GetBytes(buffer);

                SystemNet.HttpWebRequest netrequest = (SystemNet.HttpWebRequest)SystemNet.WebRequest.Create(new Uri("http://gdjwgl.bjut.edu.cn/xscjcx.aspx?xh=" + gd.StudentID + "&xm=" + "" + "&gnmkdm=N121605"));
                netrequest.Headers["Referer"] = "http://gdjwgl.bjut.edu.cn/xscjcx.aspx?xh=" + gd.StudentID + "&xm=" + "" + "&gnmkdm=N121605";
                netrequest.Method             = "POST";

                netrequest.ContentType = "application/x-www-form-urlencoded";


                HttpCookie cookie = filter.CookieManager.GetCookies(new Uri("http://gdjwgl.bjut.edu.cn/xscjcx.aspx?xh=" + gd.StudentID + "&xm=" + gd.StudentName + "&gnmkdm=N121605"))[0];


                netrequest.Headers["Cookie"] = cookie.Name + "=" + cookie.Value;

                using (Stream streamRequest = await netrequest.GetRequestStreamAsync())//从在异步调用问题,
                {
                    streamRequest.Write(bytedata, 0, bytedata.Length);
                }

                SystemNet.HttpWebResponse netrespones = (SystemNet.HttpWebResponse)(await netrequest.GetResponseAsync());

                Stream stream = netrespones.GetResponseStream();
                using (StreamReader sr = new StreamReader(stream, DBCSCodePage.DBCSEncoding.GetDBCSEncoding("gb2312")))
                {
                    string s = sr.ReadToEnd();
                    gd.gc.GetGradeChart(s);
                }

                Frame.Navigate(typeof(Grade), gd);
                //IsWorking = false;
            }
            catch (Exception ex)
            {
                await new MessageDialog(ex.Message).ShowAsync();
                //IsWorking = false;
            }
            finally
            {
                //ShowWaitingRing(false);
                progress.Hide();
            }
        }
示例#48
0
文件: Curl.cs 项目: wolfweb/Ww
 private async Task<String> GetResponseAsync(String data, HttpWebRequest client) {
     using (var response = await client.GetResponseAsync()) {
         using (var stream = response.GetResponseStream())
         using (var reader = new StreamReader(stream))
             return reader.ReadToEnd();
     }
 }
示例#49
0
文件: Peer.cs 项目: akonsand/Peer.Net
		/// <summary>
		/// Initializes the ID by sending an HTTP request to the web server.
		/// </summary>
		private async void InitializeID ()
		{
			string protocol = "http://";
			string url = protocol + this.Options.Host + ":" + this.Options.Port + this.Options.Path + this.Options.Key + "/id";
			HttpWebRequest httpWebRequest = new HttpWebRequest (new Uri (url));
			httpWebRequest.Method = "GET";
			using (WebResponse response = await httpWebRequest.GetResponseAsync ()) { 
				using (Stream stream = response.GetResponseStream ()) {
					JsonSerializer jsonSerializer = new JsonSerializer ();
					StreamReader streamReader = new StreamReader (stream);
					string id = streamReader.ReadToEnd ();
					this.Id = id;
					Initialize (id);                    
				}
			}


		}
示例#50
0
		public async Task ConnectAsync (Uri uri, CancellationToken cancellationToken)
		{
			state = WebSocketState.Connecting;
			var httpUri = new UriBuilder (uri);
			if (uri.Scheme == "wss")
				httpUri.Scheme = "https";
			else
				httpUri.Scheme = "http";
			req = (HttpWebRequest)WebRequest.Create (httpUri.Uri);
			req.ReuseConnection = true;
			if (options.Cookies != null)
				req.CookieContainer = options.Cookies;

			if (options.CustomRequestHeaders.Count > 0) {
				foreach (var header in options.CustomRequestHeaders)
					req.Headers[header.Key] = header.Value;
			}

			var secKey = Convert.ToBase64String (Encoding.ASCII.GetBytes (Guid.NewGuid ().ToString ().Substring (0, 16)));
			string expectedAccept = Convert.ToBase64String (SHA1.Create ().ComputeHash (Encoding.ASCII.GetBytes (secKey + Magic)));

			req.Headers["Upgrade"] = "WebSocket";
			req.Headers["Sec-WebSocket-Version"] = VersionTag;
			req.Headers["Sec-WebSocket-Key"] = secKey;
			req.Headers["Sec-WebSocket-Origin"] = uri.Host;
			if (options.SubProtocols.Count > 0)
				req.Headers["Sec-WebSocket-Protocol"] = string.Join (",", options.SubProtocols);

			if (options.Credentials != null)
				req.Credentials = options.Credentials;
			if (options.ClientCertificates != null)
				req.ClientCertificates = options.ClientCertificates;
			if (options.Proxy != null)
				req.Proxy = options.Proxy;
			req.UseDefaultCredentials = options.UseDefaultCredentials;
			req.Connection = "Upgrade";

			HttpWebResponse resp = null;
			try {
				resp = (HttpWebResponse)(await req.GetResponseAsync ().ConfigureAwait (false));
			} catch (Exception e) {
				throw new WebSocketException (WebSocketError.Success, e);
			}

			connection = req.StoredConnection;
			underlyingSocket = connection.socket;

			if (resp.StatusCode != HttpStatusCode.SwitchingProtocols)
				throw new WebSocketException ("The server returned status code '" + (int)resp.StatusCode + "' when status code '101' was expected");
			if (!string.Equals (resp.Headers["Upgrade"], "WebSocket", StringComparison.OrdinalIgnoreCase)
				|| !string.Equals (resp.Headers["Connection"], "Upgrade", StringComparison.OrdinalIgnoreCase)
				|| !string.Equals (resp.Headers["Sec-WebSocket-Accept"], expectedAccept))
				throw new WebSocketException ("HTTP header error during handshake");
			if (resp.Headers["Sec-WebSocket-Protocol"] != null) {
				if (!options.SubProtocols.Contains (resp.Headers["Sec-WebSocket-Protocol"]))
					throw new WebSocketException (WebSocketError.UnsupportedProtocol);
				subProtocol = resp.Headers["Sec-WebSocket-Protocol"];
			}

			state = WebSocketState.Open;
		}
示例#51
0
        /// <summary>
        /// http or https post request
        /// </summary>
        /// <param name="requestInput"></param>
        /// <param name="remoteCertificateValidationCallback"></param>
        /// <returns></returns>
        public static async Task <string> RequestPostAsync(HttpRequestArgs requestInput, Func <object, X509Certificate, X509Chain, SslPolicyErrors, bool> remoteCertificateValidationCallback = null)
        {
            var res = string.Empty;

            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(requestInput.Url);
            try
            {
                request.Method      = "POST";
                request.ContentType = string.IsNullOrEmpty(requestInput.ContentType) ? "application/x-www-form-urlencoded" : requestInput.ContentType; //application/json; encoding=utf-8
                byte[] byte1 = requestInput.GetBodyBytes().Result;
                request.ContentLength = byte1.Length;

                if (requestInput.TimeOut > 0)
                {
                    request.Timeout = requestInput.TimeOut;
                }

                if (!requestInput.Host.IsNullOrWhiteSpace())
                {
                    request.Host = requestInput.Host;
                }

                if (requestInput.Expect100Continue.HasValue)
                {
                    System.Net.ServicePointManager.Expect100Continue = requestInput.Expect100Continue.Value;
                }

                if (requestInput.KeepAlive.HasValue)
                {
                    request.KeepAlive = requestInput.KeepAlive.Value;
                }

                request.ProtocolVersion = requestInput.HttpVer;

                if (!requestInput.UserAgent.IsNullOrWhiteSpace())
                {
                    request.UserAgent = requestInput.UserAgent;
                }

                if (requestInput.DefaultConnectionLimit.HasValue)
                {
                    ServicePointManager.DefaultConnectionLimit = requestInput.DefaultConnectionLimit.Value;
                }

                if (requestInput.DnsRefreshTimeout.HasValue)
                {
                    ServicePointManager.DnsRefreshTimeout = requestInput.DnsRefreshTimeout.Value;
                }

                foreach (var header in requestInput.Headers)
                {
                    request.Headers.Add(header.Key, header.Value);
                }


                //验证服务器证书回调自动验证
                ServicePointManager.ServerCertificateValidationCallback = ((remoteCertificateValidationCallback == null) ? new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult) : new System.Net.Security.RemoteCertificateValidationCallback(remoteCertificateValidationCallback));

                using (Stream newStream = await request.GetRequestStreamAsync())
                {
                    // Send the data.
                    newStream.Write(byte1, 0, byte1.Length);    //写入参数
                }

                using (System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)(await request.GetResponseAsync()))
                {
                    Encoding coding = string.IsNullOrEmpty(requestInput.CharSet) ? System.Text.Encoding.UTF8 : System.Text.Encoding.GetEncoding(requestInput.CharSet);
                    using (System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream(), coding))
                    {
                        var responseMessage = reader.ReadToEnd();
                        if (response.StatusCode == HttpStatusCode.OK)
                        {
                            res = responseMessage;
                        }

                        response.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                res = string.Format("ERROR:{0}", ex.Message);
            }
            finally
            {
                request.Abort();
                request = null;
            }

            return(res);
        }