Пример #1
0
        private HttpWebResponse GetResponse(ConnectionOptions co, out HttpWebRequest request)
        {
            request = GetRequest(co);
            HttpWebResponse response = null;

            try
            {
                if (co.data != null && co.data.Length > 0)
                {
                    using (var stream = request.GetRequestStream())
                    {
                        stream.Write(co.data, 0, co.data.Length);
                    }
                }
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                response?.Close();
                // Try to fix a 401 exception by adding a Authorization header
                if (ex.Response == null || ((HttpWebResponse)ex.Response).StatusCode != HttpStatusCode.Unauthorized)
                {
                    return(null);
                }
                response = TryDigestRequest(co, ex);
            }
            catch (Exception ex)
            {
                Logger.LogException(ex, "Connection Factory");
                response?.Close();
                response = null;
            }

            return(response);
        }
Пример #2
0
        /// <summary>
        /// Database post request to post something to the database
        /// </summary>
        /// <param name="requestUrl">The request url</param>
        /// <param name="method">Can be either POST or PUT</param>
        /// <param name="parameters">The parameters of the request</param>
        /// <returns>True if the request succeed</returns>
        public bool DatabaseSendDataRequest(string requestUrl, string method, params string[] parameters)
        {
            bool result = false;

            //Construct the parameter string
            string postData = "";

            foreach (var item in parameters)
            {
                postData += item + "&";
            }
            postData = postData.Trim('&');
            //Prepare the payload to be written to the request stream
            var data = Encoding.ASCII.GetBytes(postData);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl);

            request.Headers[HttpRequestHeader.Authorization] = "Bearer " + Constants.DB_CREDS;
            request.Accept        = "application/json";
            request.Method        = method;
            request.ContentType   = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;
            request.Timeout       = 1800000;

            using (var stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }

            HttpWebResponse response = null;

            try
            {
                response = (HttpWebResponse)request.GetResponse();

                if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Created)
                {
                    result = true;
                }
                else
                {
                    result = false;
                }
                //Close the connection
                response?.Close();
            }
            catch (WebException e)
            {
                //Close the connections
                response?.Close();
                Log.Error(e.Message + ": " + requestUrl + ": " + postData);
            }

            return(result);
        }
Пример #3
0
        private HttpWebResponse TryDigestRequest(ConnectionOptions co, WebException ex)
        {
            HttpWebResponse response = null;

            try
            {
                var wwwAuthenticateHeader = ex.Response.Headers["WWW-Authenticate"];
                if (wwwAuthenticateHeader == null)
                {
                    return(null);
                }
                if (wwwAuthenticateHeader.StartsWith("Basic", true, CultureInfo.InvariantCulture))
                {
                    return(null); //already failed
                }
                var realm = GrabHeaderVar("realm", wwwAuthenticateHeader);
                var nonce = GrabHeaderVar("nonce", wwwAuthenticateHeader);
                var qop   = GrabHeaderVar("qop", wwwAuthenticateHeader);

                string cnonce = new Random().Next(123400, 9999999).ToString(CultureInfo.InvariantCulture);

                var request = GetRequest(co);

                string authorization = GetDigestHeader(co.source, co.username, co.password, realm, nonce, cnonce, qop);
                request.Headers["Authorization"] = authorization;

                response = (HttpWebResponse)request.GetResponse();
                Uri uri;
                if (Uri.TryCreate(co.source, UriKind.Absolute, out uri))
                {
                    if (uri != null)
                    {
                        AddDigest(new DigestConfig(uri.Host, authorization));
                    }
                }
                co.ExecuteCallback(true);
            }
            catch (ApplicationException)
            {
                //headers missing for digest
                response?.Close();
                response = null;
                co.ExecuteCallback(false);
            }
            catch (Exception ex2)
            {
                Logger.LogException(ex2, "Digest");
                response?.Close();
                response = null;
                co.ExecuteCallback(false);
            }
            return(response);
        }
Пример #4
0
        private static bool DatabaseSendDataRequest(params string[] parameters)
        {
            bool result = false;

            //Construct the parameter string
            string postData = "";

            foreach (var item in parameters)
            {
                postData += item + "&";
            }
            postData = postData.Trim('&');
            //Prepare the payload to be written to the request stream
            var data = Encoding.ASCII.GetBytes(postData);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:62020/API/AnalyzeTwitterAccount");

            request.Method        = "POST";
            request.ContentType   = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;
            request.Timeout       = 1800000;

            using (var stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }

            HttpWebResponse response = null;

            try
            {
                response = (HttpWebResponse)request.GetResponse();

                if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Created)
                {
                    result = true;
                }
                else
                {
                    result = false;
                }
                //Close the connection
                response?.Close();
            }
            catch (WebException e)
            {
                //Close the connections
                response?.Close();
            }

            return(result);
        }
Пример #5
0
        public static string GetPage(string url)
        {
            HttpWebRequest  request  = null;
            HttpWebResponse response = null;
            StreamReader    reader   = null;

            try
            {
                request                   = (HttpWebRequest)WebRequest.Create(url);
                request.UserAgent         = "www.iooin.com";
                request.Timeout           = 20000;
                request.AllowAutoRedirect = false;
                response                  = (HttpWebResponse)request.GetResponse();
                if (response.StatusCode == HttpStatusCode.OK && response.ContentLength < 1024 * 1024)
                {
                    reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("GB2312"));
                    string html = reader.ReadToEnd();
                    return(html);
                }
            }
            catch { }
            finally
            {
                response?.Close();
                reader?.Close();
                if (request != null)
                {
                    request = null;
                }
            }
            return(string.Empty);
        }
Пример #6
0
        internal string Get(string urlAddress)
        {
            HttpWebResponse response   = null;
            StreamReader    readStream = null;

            try
            {
                var request = (HttpWebRequest)WebRequest.Create(urlAddress);
                response = (HttpWebResponse)request.GetResponse();

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    var receiveStream = response.GetResponseStream();
                    if (receiveStream == null)
                    {
                        throw new NotSupportedException($"Failed to retrieve the stream for URL {urlAddress}");
                    }

                    readStream = response.CharacterSet == null
                                                ? new StreamReader(receiveStream)
                                                : new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));

                    return(readStream.ReadToEnd());
                }
            }
            finally
            {
                response?.Close();
                readStream?.Close();
            }

            return(null);
        }
Пример #7
0
        public static string Get(string url)
        {
            GC.Collect();
            string result;

            HttpWebRequest  request  = null;
            HttpWebResponse response = null;

            //请求url以获取数据
            try
            {
                //设置最大连接数
                ServicePointManager.DefaultConnectionLimit = 200;

                request = (HttpWebRequest)WebRequest.Create(url);

                request.Method = "GET";

                //获取服务器返回
                response = (HttpWebResponse)request.GetResponse();

                //获取HTTP返回数据
                // ReSharper disable once AssignNullToNotNullAttribute
                StreamReader sr = new StreamReader(stream: response.GetResponseStream(), encoding: Encoding.UTF8);
                result = sr.ReadToEnd().Trim();
                sr.Close();
            }
            finally
            {
                //关闭连接和流
                response?.Close();
                request?.Abort();
            }
            return(result);
        }
Пример #8
0
        public void TestHttpRestulSettingContentType(bool setContentTypeBrutally)
        {
            var text = "Some text";
            var url  = $"{Config.ListeningOn}/test/plaintext?SetContentType={setContentTypeBrutally}&Text={text}";

#pragma warning disable CS0618, SYSLIB0014
            var req = WebRequest.CreateHttp(url);
#pragma warning restore CS0618, SYSLIB0014

            HttpWebResponse res = null;
            try
            {
                res = (HttpWebResponse)req.GetResponse();

                var downloaded = res.GetResponseStream().ReadToEnd();

                Assert.AreEqual(text, downloaded, "Checking the downloaded string");

                Assert.AreEqual("text/plain", res.ContentType, "Checking for expected contentType");
            }
            finally
            {
                res?.Close();
            }
        }
Пример #9
0
        /// <summary>
        /// 把响应流转换为文本。
        /// </summary>
        /// <param name="rsp">响应流对象</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>响应文本</returns>
        public string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
        {
            Stream       stream = null;
            StreamReader reader = null;

            try
            {
                stream = rsp.GetResponseStream();
                if (stream == null)
                {
                    throw new ArgumentNullException(nameof(stream));
                }
                reader = new StreamReader(stream, encoding);
                return(reader.ReadToEnd());
            }
            catch (Exception er)
            {
                throw new Exception(er.Message);
            }
            finally
            {
                reader?.Close();
                stream?.Close();
                rsp?.Close();
            }
        }
        public void TestHttpRestulSettingContentType(bool setContentTypeBrutally)
        {
            var text = "Some text";
            var url  = $"{Config.ListeningOn}/test/plaintext?SetContentType={setContentTypeBrutally}&Text={text}";
            var req  = WebRequest.Create(url) as HttpWebRequest;

            HttpWebResponse res = null;

            try
            {
                res = (HttpWebResponse)req.GetResponse();

                string downloaded;
                using (StreamReader s = new StreamReader(res.GetResponseStream()))
                {
                    downloaded = s.ReadToEnd();
                }

                Assert.AreEqual(text, downloaded, "Checking the downloaded string");

                Assert.AreEqual("text/plain", res.ContentType, "Checking for expected contentType");
            }
            finally
            {
                res?.Close();
            }
        }
Пример #11
0
        public void TestHttpRestulSettingContentType(bool setContentTypeBrutally)
        {
            string         text = "Some text";
            string         url  = string.Format("{0}/test/plaintext?SetContentTypeBrutally={1}&Text={2}", ListeningOn, setContentTypeBrutally, text);
            HttpWebRequest req  = WebRequest.CreateHttp(url);

            HttpWebResponse res = null;

            try
            {
                res = (HttpWebResponse)req.GetResponse();

                string downloaded;
                using (StreamReader s = new StreamReader(res.GetResponseStream()))
                {
                    downloaded = s.ReadToEnd();
                }

                Assert.AreEqual(text, downloaded, "Checking the downloaded string");

                Assert.AreEqual("text/plain", res.ContentType, "Checking for expected contentType");
            }
            finally
            {
                res?.Close();
            }
        }
Пример #12
0
        public string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
        {
            StringBuilder stringBuilder = new StringBuilder();
            Stream        stream        = null;
            StreamReader  streamReader  = null;

            try
            {
                stream       = rsp.GetResponseStream();
                streamReader = new StreamReader(stream, encoding);
                int num = -1;
                while ((num = streamReader.Read()) > -1)
                {
                    char c = (char)num;
                    if (c != 0)
                    {
                        stringBuilder.Append(c);
                    }
                }
            }
            finally
            {
                streamReader?.Close();
                stream?.Close();
                rsp?.Close();
            }
            return(stringBuilder.ToString());
        }
Пример #13
0
        private TReturnType GetWebResponse <TReturnType>(WebRequest wr)
        {
            HttpWebResponse resp        = null;
            var             returnValue = default(TReturnType);

            try
            {
                resp = (HttpWebResponse)wr.GetResponse();
                var respStream = resp.GetResponseStream();

                if (respStream != null)
                {
                    var resultString = new StreamReader(respStream).ReadToEnd();

                    try
                    {
                        returnValue = (new JsonSerializer()).Deserialize <TReturnType>(new JsonTextReader(new StringReader(resultString)));
                    }
                    catch (Exception ex)
                    {
                        throw new Exception($"Unexpected error in JsonDeseralization: {ex.Message}");
                    }
                }
            }
            catch (Exception except)
            {
                throw new Exception($"Exception in getting response from PokeApi: {except.Message}");
            }
            finally
            {
                resp?.Close();
            }

            return(returnValue);
        }
Пример #14
0
        private async Task PageHasCertificate(string url)
        {
            // if site has certificate than it will load by https://
            url = url.Replace("http://", "https://");
            try
            {
                if (WebRequest.Create(url) is HttpWebRequest request)
                {
                    request.Method = "HEAD";
                    HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse;

                    response?.Close();
                }

                siteAddress.Text  = url;
                pageHasCerificate = true;
            }
            catch (NullReferenceException exception)
            {
                CustomMessages.DisplayCustomErrorMsg("NullReferenceException", exception.Message);
                pageHasCerificate = false;
            }
            catch (Exception exception)
            {
                CustomMessages.DisplayCustomErrorMsg("UnrecognizedException", exception.Message);
                pageHasCerificate = false;
            }

            // TODO: Obsługa poszczególnych wyjątków, tak aby poinformować użytkownika nie tylko o tym, że nie udało się nawiązać połączenia, ale również czemu to się nie udało
        }
Пример #15
0
        public ApiResponse Head(string endpoint, List <string> parameters)
        {
            var url = BuildEndpointUrl(endpoint, parameters);

            WebRequest request = WebRequest.Create(url);

            SetBasicAuthHeader(request);

            HttpWebResponse response = null;

            try
            {
                request.Method = "HEAD";
                response       = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                if (ex.Response == null)
                {
                    return(new ApiResponse(HttpStatusCode.InternalServerError, null));
                }
                return(new ApiResponse(((HttpWebResponse)ex.Response).StatusCode, null));
            }
            finally
            {
                response?.Close();
            }

            return(new ApiResponse(response.StatusCode, null));
        }
Пример #16
0
        public ApiResponse Get(string endpoint, List <string> parameters)
        {
            var url = BuildEndpointUrl(endpoint, parameters);

            WebRequest request = WebRequest.Create(url);

            SetBasicAuthHeader(request);

            HttpWebResponse response       = null;
            dynamic         responseObject = null;
            StreamReader    reader         = null;
            Stream          dataStream     = null;

            try
            {
                response   = (HttpWebResponse)request.GetResponse();
                dataStream = response.GetResponseStream();
                reader     = new StreamReader(dataStream);
                string responseFromServer = reader.ReadToEnd();
                responseObject = JsonConvert.DeserializeObject <dynamic>(responseFromServer);
            }
            catch (WebException ex)
            {
                return(new ApiResponse(((HttpWebResponse)ex.Response).StatusCode, null));
            }
            finally
            {
                reader?.Close();
                dataStream?.Close();
                response?.Close();
            }

            return(new ApiResponse(response.StatusCode, responseObject));
        }
Пример #17
0
        public void Obligations_LinksAreNotBroken()
        {
            // Arrange
            var obligations = _obligationLoader.GetObligations()
                              .Where(o => o.Link != null);

            foreach (var obligation in obligations)
            {
                // from alternative answer to http://stackoverflow.com/questions/924679/c-sharp-how-can-i-check-if-a-url-exists-is-valid

                HttpWebResponse response = null;
                try
                {
                    // Act
                    var request = (HttpWebRequest)WebRequest.Create(obligation.Link.Url);
                    request.Method = "HEAD";
                    response       = request.GetResponse() as HttpWebResponse;
                    // Assert
                    Assert.IsNotNull(response);
                    Assert.AreEqual(response.StatusCode, HttpStatusCode.OK, "Broken link: " + obligation.Link.Url + " in " + obligation.Id);
                }
                catch
                {
                    Assert.Fail("Bad link in " + obligation.Id);
                }
                finally
                {
                    response?.Close();
                }
            }
        }
Пример #18
0
        private HttpStatusCode GetStatusCode(string url)
        {
            HttpWebRequest  req = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse res = null;
            HttpStatusCode  statusCode;

            try
            {
                res        = (HttpWebResponse)req.GetResponse();
                statusCode = res.StatusCode;
            }
            catch (WebException ex)
            {
                res = (HttpWebResponse)ex.Response;

                if (res != null)
                {
                    statusCode = res.StatusCode;
                }
                else
                {
                    throw;
                }
            }
            finally
            {
                res?.Close();
            }
            return(statusCode);
        }
Пример #19
0
        public static HttpWebResponse GetResponse(string source, string cookies, string headers, string userAgent, IWebProxy proxy, bool useHttp10, bool useSeparateConnectionGroup, int requestTimeout, string username, string password, bool post, out HttpWebRequest request)
        {
            request = GetRequest(source, cookies, headers, userAgent, proxy, useHttp10, useSeparateConnectionGroup, requestTimeout, username, password, post);
            HttpWebResponse response = null;

            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                // Try to fix a 401 exception by adding a Authorization header
                if (ex.Response == null || ((HttpWebResponse)ex.Response).StatusCode != HttpStatusCode.Unauthorized)
                {
                    return(null);
                }
                response?.Close();

                response = TryDigestRequest(source, cookies, headers, userAgent, proxy, useHttp10, useSeparateConnectionGroup, requestTimeout, username, password, post, ex);
            }
            catch
            {
                response = null;
            }

            return(response);
        }
Пример #20
0
        public static bool UrlExists(string url)
        {
            var webRequest = WebRequest.Create(url);

            webRequest.Timeout = 1200;
            webRequest.Method  = "HEAD";

            HttpWebResponse response = null;

            try {
                using (response = (HttpWebResponse)webRequest.GetResponse()) {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        return(true);
                    }
                }
            }
            catch {
                // ignored
            }
            finally {
                response?.Close();
            }

            return(false);
        }
Пример #21
0
        public async Task GetResponseAsync(HttpListenerContext context, string localBaseUrl, string remoteBaseUrl, CancellationToken ct) {
            string postUri = null;

            if (context.Request.IsWebSocketRequest) {
                UriBuilder ub = new UriBuilder(PostUri) { Scheme = "wss" };
                postUri = ub.Uri.ToString();
            } else {
                postUri = PostUri.ToString();
            }

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postUri);
            request.Method = context.Request.HttpMethod;
            request.ServerCertificateValidationCallback += ValidateCertificate;

            if (!context.Request.IsWebSocketRequest) {
                SetRequestHeaders(request, context.Request.Headers, localBaseUrl, remoteBaseUrl);
            }

            // Add RTVS headers
            var remoteUri = GetRemoteUri(context.Request.Url, remoteBaseUrl);
            request.Headers.Add(CustomHttpHeaders.RTVSRequestedURL, remoteUri.ToString());

            if (context.Request.ContentLength64 > 0) {
                using (Stream reqStream = await request.GetRequestStreamAsync()) {
                    await context.Request.InputStream.CopyAndFlushAsync(reqStream, null, ct);
                }
            }

            HttpWebResponse response = null;
            try {
                response = (HttpWebResponse)await request.GetResponseAsync();
                if (response != null) {
                    if (context.Request.IsWebSocketRequest && response.StatusCode == HttpStatusCode.SwitchingProtocols) {
                        Stream respStream = response.GetResponseStream();
                        string subProtocol = response.Headers[Constants.Headers.SecWebSocketProtocol];
                        var remoteWebSocket = CommonWebSocket.CreateClientWebSocket(respStream, subProtocol, TimeSpan.FromMinutes(10), receiveBufferSize: 65335, useZeroMask: true);
                        var websocketContext = await context.AcceptWebSocketAsync(subProtocol, receiveBufferSize: 65335, keepAliveInterval: TimeSpan.FromMinutes(10));
                        await WebSocketHelper.SendReceiveAsync(websocketContext.WebSocket, remoteWebSocket, ct);
                    } else {
                        context.Response.StatusCode = (int)response.StatusCode;
                        SetResponseHeaders(response, context.Response, localBaseUrl, remoteBaseUrl);
                        using (Stream respStream = response.GetResponseStream())
                        using (Stream outStream = context.Response.OutputStream) {
                            await respStream.CopyAndFlushAsync(outStream, null, ct);
                        }
                        response.Close();
                    }
                }
            } catch (WebException wex) when (wex.Status == WebExceptionStatus.ProtocolError) {
                response = wex.Response as HttpWebResponse;
            } catch (OperationCanceledException) {
                WebServer.Stop(remoteUri.Port);
            } catch (Exception ex) when (!ex.IsCriticalException()) {
                _log?.WriteLine(LogVerbosity.Normal, MessageCategory.Error, Resources.Error_RemoteWebServerException.FormatInvariant(ex.Message));
                _console?.WriteErrorLine(Resources.Error_RemoteWebServerException.FormatInvariant(ex.Message));
                WebServer.Stop(remoteUri.Port);
            } finally {
                response?.Close();
            }
        }
Пример #22
0
        /// <summary>
        /// Отправка сообщений
        /// </summary>
        public void Send()
        {
            HttpWebResponse res = null;
            StreamReader    sr  = null;

            try
            {
                string         xmlDoc = CreateXML();
                string         url    = $"{_ServerIP}:{_NumPort}";
                HttpWebRequest req    = (HttpWebRequest)WebRequest.Create(url);
                req.Method      = "POST";
                req.ContentType = "text/xml;charset=utf-8";
                byte[] requestBytes = System.Text.Encoding.ASCII.GetBytes(xmlDoc);
                req.ContentLength = requestBytes.Length;
                Stream requestStream = req.GetRequestStream();
                requestStream.Write(requestBytes, 0, requestBytes.Length);
                requestStream.Close();

                res = (HttpWebResponse)req.GetResponse();
                sr  = new StreamReader(res.GetResponseStream(), System.Text.Encoding.Default);
                string backstr = sr.ReadToEnd();
                GetSend(backstr);
            }
            catch (Exception ex)
            {
                //MessageBox.Show("Error: " + ex.Message);
            }
            finally
            {
                sr?.Close();
                res?.Close();
            }
        }
Пример #23
0
        public String GetHttpResponse(String url)
        {
            //HttpResponseMessage response = this.httpClient.GetAsync(url).Result;
            //String res = response.Content.ReadAsStringAsync().Result;
            //return res;
            string          content   = "";
            HttpWebRequest  HttpWReq  = null;
            HttpWebResponse HttpWResp = null;

            try
            {
                HttpWReq =
                    (HttpWebRequest)WebRequest.Create(url);
                HttpWReq.UserAgent = "MSIE6.0";
                HttpWReq.Method    = "GET";

                HttpWResp = (HttpWebResponse)HttpWReq.GetResponse();
                Stream resStream = HttpWResp.GetResponseStream();

                using (StreamReader sr = new StreamReader(resStream))
                {
                    content = sr.ReadToEnd();
                }
                // Insert code that uses the response object.
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                HttpWResp?.Close();
            }
            return(content);
        }
Пример #24
0
 public override void Close()
 {
     bufferedStream?.Close();
     responseStream?.Close();
     response?.Close();
     base.Close();
 }
Пример #25
0
        private static void TranslateRequestCallBack(IAsyncResult ar)
        {
            var             pair     = (KeyValuePair <WebRequest, TranslateCallBack>)ar.AsyncState;
            var             request  = pair.Key;
            var             callback = pair.Value;
            HttpWebResponse response = null;

            try
            {
                response = (HttpWebResponse)request.EndGetResponse(ar);
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    callback(false, $"Response is failed with code: {response.StatusCode}");
                    return;
                }

                using (var stream = response.GetResponseStream())
                {
                    var succeed = ReadGoogleTranslatedResult(stream, out var output);

                    callback(succeed, output);
                }
            }
            catch (Exception ex)
            {
                callback(false, $"Request failed.\r\n{ex.Message}");
            }
            finally
            {
                response?.Close();
            }
        }
Пример #26
0
        public string GetOAuthToken(string requestUriString)
        {
            var requestStopWatch = Stopwatch.StartNew();

            try
            {
                HttpWebRequest req =
                    (HttpWebRequest)WebRequest.Create(requestUriString);
                req.Method       = "POST";
                req.Timeout      = Timeout.Infinite;
                req.KeepAlive    = true;
                EndpointResponse = (HttpWebResponse)req.GetResponse();
                requestStopWatch.Stop();
                double ResponseTime = requestStopWatch.Elapsed.TotalMilliseconds;
                Console.WriteLine($"Time taken by OAuth request to execute is : {ResponseTime} ms ");
                return(GetTokenFromResponse());
            }
            catch (WebException failedRequest)
            {
                Console.WriteLine($"Request failed due to error : {failedRequest.Message}");
                throw;
            }
            finally
            {
                EndpointResponse?.Close();
            }
        }
Пример #27
0
        public HttpWebResponse RequestFile(AuthenticationBase authentication, string address, string httpMethod = "GET")
        {
            HttpWebResponse response = null;

            try
            {
                var request = (HttpWebRequest)WebRequest.Create(address);

                request.UserAgent = "VSTS-Get";
                request.Headers.Set(HttpRequestHeader.Authorization, GetAuthenticationHeaderValue(authentication).ToString());
                request.ContentType = "application/json";
                request.Method      = httpMethod;

                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException e)
            {
                if (e.Status == WebExceptionStatus.ProtocolError)
                {
                    response = (HttpWebResponse)e.Response;
                }
            }
            catch (Exception)
            {
                response?.Close();
            }

            return(response);
        }
Пример #28
0
        public static bool UrlExists(string file)
        {
            bool            exists   = false;
            HttpWebResponse response = null;
            var             request  = (HttpWebRequest)WebRequest.Create(file);

            request.Method            = "HEAD";
            request.Timeout           = 5000; // milliseconds
            request.AllowAutoRedirect = false;

            try
            {
                response = (HttpWebResponse)request.GetResponse();
                exists   = response.StatusCode == HttpStatusCode.OK;
            }
            catch
            {
                exists = false;
            }
            finally
            {
                // close your response.
                response?.Close();
            }
            return(exists);
        }
Пример #29
0
        /// <summary>
        /// Start sending the <see cref="DeliverMessage"/>
        /// </summary>
        /// <param name="envelope"></param>
        public async Task <SendResult> SendAsync(DeliverMessageEnvelope envelope)
        {
            if (envelope == null)
            {
                throw new ArgumentNullException(nameof(envelope));
            }

            if (String.IsNullOrWhiteSpace(envelope.ContentType))
            {
                throw new InvalidOperationException(
                          $"{nameof(HttpSender)} requires a ContentType to correctly deliver the message");
            }

            Logger.Info($"(Deliver)[{envelope.Message.MessageInfo.MessageId}] Send DeliverMessage to {Location}");

            HttpWebRequest request = await CreateHttpPostRequest(envelope.ContentType, envelope.SerializeMessage()).ConfigureAwait(false);

            HttpWebResponse response = await SendHttpPostRequest(request).ConfigureAwait(false);

            HttpStatusCode statusCode = response?.StatusCode ?? HttpStatusCode.InternalServerError;

            Logger.Debug($"POST DeliverMessage to {Location} result in: {(int)statusCode} {response?.StatusCode}");

            response?.Close();
            return(SendResultUtils.DetermineSendResultFromHttpResonse(statusCode));
        }
        public static Bitmap GetBossImage(string bossname)
        {
            HttpWebResponse wresp    = null;
            Stream          mystream = null;
            Bitmap          bmp      = null;

            try
            {
                var wreq = (HttpWebRequest)WebRequest.Create(
                    "https://raw.githubusercontent.com/ImSpare/Maplestory2BossOverlay/master/images/" + bossname +
                    ".png");
                wreq.AllowWriteStreamBuffering = true;

                wresp = (HttpWebResponse)wreq.GetResponse();

                if ((mystream = wresp.GetResponseStream()) != null)
                {
                    bmp = new Bitmap(mystream);
                }
            }
            catch
            {
                // ignored happens if server has issues or something
            }
            finally
            {
                mystream?.Close();

                wresp?.Close();
            }

            return(bmp);
        }
Пример #31
0
        public HTTPPost(Uri Url, Dictionary<string, string> Parameters)
        {
            StringBuilder respBody = new StringBuilder();

            request = (HttpWebRequest)HttpWebRequest.Create(Url);
            request.UserAgent = "Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1C10 Safari/419.3";
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            string content = "?";
            foreach (string k in Parameters.Keys)
            {
                content += k + "=" + Parameters[k] + "&";
            }
            content = content.TrimEnd(new char[] { '&' });
            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] byte1 = encoding.GetBytes(content);
            request.ContentLength = byte1.Length;
            byte[] buf = new byte[8192];
            using (Stream rs = request.GetRequestStream())
            {
                rs.Write(byte1, 0, byte1.Length);
                rs.Close();

                response = (HttpWebResponse)request.GetResponse();
                Stream respStream = response.GetResponseStream();

                int count = 0;
                do
                {
                    count = respStream.Read(buf, 0, buf.Length);
                    if (count != 0)
                        respBody.Append(Encoding.ASCII.GetString(buf, 0, count));
                }
                while (count > 0);

                respStream.Close();
                ResponseBody = respBody.ToString();
                EscapedBody = GetEscapedBody();
                StatusCode = GetStatusLine();
                Headers = GetHeaders();

                response.Close();
            }
        }