// 에셋 토큰 얻기
        public bool GetAccessToken()
        {
            try
            {
                request  = (HttpWebRequest)WebRequest.Create(GlobalApiEndPoint.KAKAO_URL_ACCESSTOKEN + GlobalKakaoData.userToken);
                response = (HttpWebResponse)request.GetResponse();

                stream = response.GetResponseStream();
                string sResult = new StreamReader(stream).ReadToEnd();
                var    jResult = JObject.Parse(sResult);

                GlobalKakaoData.accessToken = jResult["access_token"].ToString();
                GlobalKakaoData.header      = "Bearer " + GlobalKakaoData.accessToken;

                GlobalState.isLogin = true;

                StatusDisplay status = new StatusDisplay("로그인 성공!", StatusDisplay.enumType.Success);

                response.Dispose();
                stream.Dispose();

                return(true);
            }
            catch
            {
                StatusDisplay status = new StatusDisplay("로그인을 하지 않았습니다.", StatusDisplay.enumType.Warning);
                if (response != null)
                {
                    response.Dispose();
                    stream.Dispose();
                }

                return(false);
            }
        }
        public async Task <AvrHttpResponse> SendHttpRequest()
        {
            WebRequest request = HttpWebRequest.Create(Uri);

            request.Method      = "POST";
            request.ContentType = "text/xml";
            Stream stream = await request.GetRequestStreamAsync();

            using (var streamWriter = new StreamWriter(stream))
            {
                streamWriter.Write(mXMLString);
                streamWriter.Flush();
            }

            HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse;

            string         responseString = "";
            HttpStatusCode responseStatus = response.StatusCode;

            if (responseStatus != HttpStatusCode.OK)
            {
                response.Dispose();
                return(new AvrHttpResponse(responseStatus, responseString));
            }

            // process the response
            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                responseString = await reader.ReadToEndAsync();
            }
            response.Dispose();
            return(new AvrHttpResponse(responseStatus, responseString));
        }
Beispiel #3
0
 public IWebResponseMessage EnsureSuccessStatusCode()
 {
     if (_response == null)
     {
         throw new WebClientException("Response is null.");
     }
     if (!IsSuccessStatusCode)
     {
         WebException webException;
         if (((int)_response.StatusCode) == 0 && Exception == null)
         {
             webException = new WebException($"Error getting a response: {ReasonPhrase}.");
         }
         else if (Exception is WebException wException)
         {
             webException = wException;
         }
         else
         {
             webException = new WebException($"The remove server returned an error: ({(int)_response.StatusCode}) {ReasonPhrase}.");
         }
         var faultedResponse = new FaultedResponse(this);
         _response.Dispose();
         _response = null;
         throw new WebClientException(webException.Message, webException, faultedResponse);
     }
     return(this);
 }
        public async Task <AvrHttpResponse> SendHttpRequest()
        {
            WebRequest request = HttpWebRequest.Create(Uri);

            request.Method = "GET";

            HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse;

            string         responseString = "";
            HttpStatusCode responseStatus = response.StatusCode;

            if (responseStatus != HttpStatusCode.OK)
            {
                response.Dispose();
                return(new AvrHttpResponse(responseStatus, responseString));
            }

            // process the response
            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                responseString = await reader.ReadToEndAsync();
            }
            response.Dispose();
            return(new AvrHttpResponse(responseStatus, responseString));
        }
Beispiel #5
0
 private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
 {//下载任务完成
     if (e.Error != null)
     {
         //出现错误
         MessageBox.Show(e.Error.Message);
         response.Dispose();
     }
     else if (e.Cancelled)
     {
         //中止下载
         MessageBox.Show($"下载暂停,下载的文件地址为:{downLoadPath} ,共下载{DownLoadSize}字节");
         response.Close();
         fileStream.Close();
         btnDown.Enabled  = true;
         btnPause.Enabled = false;
     }
     else
     {
         //完成
         MessageBox.Show($"下载完毕! 本地地址为:{downLoadPath}");
         response.Dispose();
         fileStream.Dispose();
         btnDown.Enabled  = false;
         btnPause.Enabled = false;
     }
 }
Beispiel #6
0
        public static GameHeader MakeHeadRequest(string TitleID)
        {
            HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(NucleusURL + $"?title_id={TitleID}");

            Request.Method = "HEAD";
            HttpWebResponse Response = (HttpWebResponse)Request.GetResponse();

            if (Response.Headers.Get("X-GCN-Status-Code") == "Success")
            {
                JObject JSON = JObject.Parse(Response.Headers.Get("X-GCN-Game-Meta"));
                Response.Dispose();

                return(new GameHeader
                {
                    Return = ReturnType.Success,
                    GameName = JSON["applications"][0]["name"].ToString(),
                    Publisher = (JSON.ContainsKey("publisher")) ? JSON["publisher"]["name"].ToString() : ""
                });
            }
            else
            {
                switch (Response.Headers.Get("X-GCN-Failure"))
                {
                case "MISSING_TITLE": Response.Dispose(); return(new GameHeader {
                        Return = ReturnType.MissingTitle, GameName = null, Publisher = null
                    });

                case "INVALID_TITLE": Response.Dispose(); return(new GameHeader {
                        Return = ReturnType.InvalidTitle, GameName = null, Publisher = null
                    });

                default: throw new NotImplementedException();
                }
            }
        }
Beispiel #7
0
        public async void SendSmsToPhone(TextBox textBox, ListBox listBox)
        {
            string         firstUrl    = "https://api.gotinder.com/v2/auth/sms/send?auth_type=sms&locale=ru";
            string         secondUrl   = "https://api.gotinder.com/v2/auth/sms/validate?auth_type=sms&locale=ru";
            string         threeUrl    = "https://api.gotinder.com/v2/auth/login/sms?locale=ru";
            string         phoneNumber = textBox.Text;
            HttpWebRequest request     = WebRequest.Create(firstUrl) as HttpWebRequest;

            request.Method      = "POST";
            request.ContentType = "application/json";
            request.UserAgent   = "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36";
            CookieContainer cookieContainer = new CookieContainer();
            // string login = "******";
            // string password = "******";
            RootDataFirstRequest dataFirstRequest = new RootDataFirstRequest();

            dataFirstRequest.phone_number = phoneNumber;
            var firstJsonData = Newtonsoft.Json.JsonConvert.SerializeObject(dataFirstRequest);

            // string data = $"login={login}&password={password}&s_post=QbAido4SpJuI9cct54vSwPPUxZbwn8QU&level=false";
            // byte[] dataBytes = Encoding.UTF8.GetBytes(firstJsonData);
            //  request.ContentLength = dataBytes.Length;
            request.CookieContainer = cookieContainer;
            using (StreamWriter writer = new StreamWriter(await request.GetRequestStreamAsync()))
            {
                // await writer.WriteAsync(dataBytes, 0, dataBytes.Length);
                await writer.WriteAsync(firstJsonData);
            }
            HttpWebResponse response = null;

            try
            {
                response = await request.GetResponseAsync() as HttpWebResponse;

                string content = "";
                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {
                    content = await reader.ReadToEndAsync();

                    reader.Close();
                }
                listBox.Items.Add($"[{DateTime.Now}]: Код отправлен на номер");
                listBox.Items.Add($"[{DateTime.Now}]: Debug: {content}");
                response.Close();
                response.Dispose();
            }
            catch (WebException webException)
            {
                MessageBox.Show(webException.Message);
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
            finally
            {
                response.Close();
                response.Dispose();
            }
        }
Beispiel #8
0
 private async Task <HttpWebResponse> Redirect <TData>(HttpWebRequest request, HttpWebResponse returnResponse, Dictionary <string, string> headers, TData data, bool showLog)
 {
     if (returnResponse.StatusCode == HttpStatusCode.Found || returnResponse.StatusCode == HttpStatusCode.Redirect ||
         returnResponse.StatusCode == HttpStatusCode.RedirectMethod)     //change method from POST => GET
     {
         returnResponse.Dispose();
         returnResponse = await this.SendRequestRecursive(returnResponse.Headers["Location"], "GET", null, String.Empty, showLog);
     }
     else if (returnResponse.StatusCode == HttpStatusCode.RedirectKeepVerb ||
              returnResponse.StatusCode == HttpStatusCode.TemporaryRedirect)
     {
         returnResponse.Dispose();
         if (data is string)
         {
             returnResponse = await this.SendRequestRecursive(returnResponse.Headers["Location"],
                                                              request.Method, headers, data as string, showLog);
         }
         else if (data is byte[])
         {
             returnResponse = await this.SendRequestRecursive(returnResponse.Headers["Location"],
                                                              request.Method, headers, data as byte[], showLog);
         }
     }
     return(returnResponse);
 }
Beispiel #9
0
        private static async Task <HttpWebResponse> GetResponse(WebRequest request)
        {
            HttpWebResponse response = null;

            try {
                response = (HttpWebResponse)await request.GetResponseAsync();

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    throw new HttpStatusCodeException(response.StatusCode, response.StatusDescription);
                }

                return(response);
            }
            catch (WebException error) when(error.Response is HttpWebResponse errorResponse)
            {
                if (SafeCodes.Any(x => x == errorResponse.StatusCode))
                {
                    return(errorResponse);
                }

                response?.Dispose();
                throw new HttpStatusCodeException(errorResponse.StatusCode, errorResponse.StatusDescription);
            }
            catch {
                response?.Dispose();
                throw;
            }
        }
Beispiel #10
0
        private async void Auth(string phone, string token, ListBox logList)
        {
            string         firstUrl    = "https://api.gotinder.com/v2/auth/sms/send?auth_type=sms&locale=ru";
            string         secondUrl   = "https://api.gotinder.com/v2/auth/sms/validate?auth_type=sms&locale=ru";
            string         threeUrl    = "https://api.gotinder.com/v2/auth/login/sms?locale=ru";
            string         phoneNumber = phone;
            HttpWebRequest request     = WebRequest.Create(threeUrl) as HttpWebRequest;

            request.Method      = "POST";
            request.ContentType = "application/json";
            request.UserAgent   = "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36";
            CookieContainer cookieContainer = new CookieContainer();
            // string login = "******";
            // string password = "******";
            RootDataThree dataFirstRequest = new RootDataThree();

            dataFirstRequest.phone_number  = phoneNumber;
            dataFirstRequest.refresh_token = token;
            var firstJsonData = Newtonsoft.Json.JsonConvert.SerializeObject(dataFirstRequest);

            request.CookieContainer = cookieContainer;
            using (StreamWriter writer = new StreamWriter(await request.GetRequestStreamAsync()))
            {
                await writer.WriteAsync(firstJsonData);
            }
            HttpWebResponse response = null;

            try
            {
                response = await request.GetResponseAsync() as HttpWebResponse;

                string content = string.Empty;
                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {
                    content = await reader.ReadToEndAsync();

                    reader.Close();
                }
                response.Close();
                response.Dispose();
                RootMetaData rootMetaData = JsonConvert.DeserializeObject <RootMetaData>(content);
                ApiToken = rootMetaData.Data.api_token;
                accountInformation.SaveTokenToFile(phoneNumber, ApiToken);
                logList.Items.Add($"Загружен в файл: {phoneNumber} - {ApiToken}");
            }
            catch (WebException webException)
            {
                MessageBox.Show(webException.Message);
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
            finally
            {
                response.Close();
                response.Dispose();
            }
        }
Beispiel #11
0
 internal void StopDownload()
 {
     try { readStream?.Dispose(); } catch { }
     try { webResponse?.Dispose(); } catch { }
     try { writeStream?.Dispose(); } catch { }
     webRequest = null;
     Status     = DownloadStatus.Aborted;
 }
Beispiel #12
0
        public async Task GetReceivedMessage()
        {
            //НАПИСАТЬ МЕТОД НА ВАЛИДАЦИЮ ТОКЕНА ККАУНТА
            List <string> tokenCollection = accountInformation.GetTokenFromFile();
            int           countFileData   = 0;
            string        url             = "https://api.gotinder.com/v2/matches?count=100&is_tinder_u=false&locale=ru&message=1";

            for (int i = 0; i < tokenCollection.Count; i++)
            {
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                request.Method      = "GET";
                request.UserAgent   = "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36";
                request.ContentType = "application/json";
                //ApiToken
                request.Headers.Add("X-Auth-Token", tokenCollection[i]);
                //   requestSecond.Headers.Add("X-Supported-Image-Formats", "webp,jpeg");
                HttpWebResponse response = null;
                try
                {
                    response = await request.GetResponseAsync() as HttpWebResponse;

                    string content = string.Empty;
                    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                    {
                        content = await reader.ReadToEndAsync();

                        reader.Close();
                    }
                    response.Close();
                    response.Dispose();
                    matchesNewRootObjectCollection.Add(JsonConvert.DeserializeObject <MatchesNewRootObject>(content));
                    if (matchesNewRootObjectCollection[0].Data.next_page_token != null)
                    {
                        NextPageToken = matchesNewRootObjectCollection[0].Data.next_page_token;
                    }
                    if (matchesNewRootObjectCollection[0].Data.Matches.Count > 0)
                    {
                        for (int j = 0; j < matchesNewRootObjectCollection[i].Data.Matches.Count; j++)
                        {
                            likesUserIdCollection.Add(matchesNewRootObjectCollection[i].Data.Matches[j].id);
                        }
                    }
                }
                catch (Exception exp)
                {
                    MessageBox.Show("Аккаунт удален или его не существует", exp.Message);
                }
                finally
                {
                    response.Close();
                    response.Dispose();
                }
            }
        }
Beispiel #13
0
        public static bool PosttoLogin(string postdata)
        {
            try
            {
                byte[]         data = Encoding.ASCII.GetBytes(postdata);
                string         cookie;
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(Program.sGloableDomailUrl + "/User/login");
                myRequest.Method          = "POST";
                myRequest.UserAgent       = Program.DefaultUserAgent;
                myRequest.ContentType     = "application/x-www-form-urlencoded";
                myRequest.ContentLength   = data.Length;
                myRequest.CookieContainer = new CookieContainer();
                myRequest.CookieContainer = Program.MLBCookie;
                //如果允许重定向 就获取不到cookie和302的状态码
                myRequest.AllowAutoRedirect = false;
                //MessageBox.Show(Program.JasperCookie.GetCookieHeader(new Uri(Program.sCookHeader)).Trim('\n').Trim('\r'));
                //myRequest.CookieContainer.SetCookies(new Uri(Program.sCookHeader), Program.JasperCookie.GetCookieHeader(new Uri(Program.sCookHeader)));
                Stream newStream = myRequest.GetRequestStream();
                newStream.Write(data, 0, data.Length);
                newStream.Close();
                HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();


                ///**/
                //StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                //string ttttt = reader.ReadToEnd();
                //System.Diagnostics.Debug.WriteLine(ttttt + "\r\n");
                ///**/

                if (myResponse.StatusCode == HttpStatusCode.Found)
                {
                    string a = myResponse.GetResponseHeader("Set-Cookie");
                    cookie = myResponse.Headers.Get("Set-Cookie");
                    SetUserId(cookie);
                    Program.MLBCookie.SetCookies(new Uri(Program.sGloableDomailUrl), cookie);
                    myResponse.Dispose();
                    myResponse.Close();

                    return(true);
                }
                else
                {
                    myResponse.Dispose();
                    myResponse.Close();
                    return(false);
                }
            }
            catch (Exception e)
            {
                string err = e.Message.ToString();
                return(false);
            }
        }
 protected virtual void Dispose(bool disposing)
 {
     if (!_disposed)
     {
         if (disposing)
         {
             if (_response != null)
             {
                 _response.Dispose();
             }
             _disposed = true;
         }
     }
 }
        public async void Run()
        {
            Setup();

            if (boundaryBytes == null)
            {
                throw new Exception("boundaryBytes was null");
            }

            HttpWebResponse resp = ReturnHttpResponse(url);

            if (resp.StatusCode != HttpStatusCode.OK)
            {
                throw new Exception("HTTP Request returned a " + resp.StatusCode + " status code");
            }

            BinaryReader reader = new BinaryReader(resp.GetResponseStream());

            while (reader.BaseStream.CanRead && !EndCaputre)
            {
                String header = ReadHeader(reader); //moves the stream on, and extracts the header
                if (EndCaputre)
                {
                    return;
                }
                int contentLength = GetContentLength(header);

                byte[] img = reader.ReadBytes(contentLength);

                if (asyncrohous)
                {
                    await OnFileCreateAsync(img);
                }
                else
                {
                    OnFileCreate(img);
                }

                if ((stopwatch != null && stopwatch.Elapsed.Minutes == minutesToRun) || singleImageExtraction)
                {
                    resp.Dispose();
                    reader.Dispose();
                    return;
                }
            }//while stream.CanRead

            resp.Dispose();
            reader.Dispose();
        }//Run
        private T GetList <T>(string url) where T : new()
        {
            T data = new T();

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

                request.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0";

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

                using (Stream inputStream = response.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(inputStream);
                    string       html   = reader.ReadToEnd();
                    reader.Dispose();
                    data = JsonConvert.DeserializeObject <T>(html);
                }

                response.Dispose();
            }
            catch (Exception ex)
            {
                Logger.Fatal(ex);

                return(new T());
            }

            return(data);
        }
Beispiel #17
0
        protected string HttpPost(string method, string url, string data)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);

            request.Method      = method;
            request.ContentType = "application/json;charset=utf-8";
            //request.ContentType = "application/x-www-form-urlencoded";

            byte[] postdatabyte = Encoding.UTF8.GetBytes(data);
            request.ContentLength = postdatabyte.Length;

            Stream requestStream = request.GetRequestStream();

            requestStream.Write(postdatabyte, 0, postdatabyte.Length);

            HttpWebResponse response       = (HttpWebResponse)request.GetResponse();
            Stream          responseStream = response.GetResponseStream();
            StreamReader    streamReader   = new StreamReader(responseStream);
            string          strResponse    = streamReader.ReadToEnd();

            Console.WriteLine(strResponse);
            requestStream.Dispose();
            response.Dispose();
            responseStream.Dispose();
            streamReader.Dispose();
            return(strResponse);
        }
Beispiel #18
0
        internal static async Task <HttpResponse> GetResponseAsync <T>(Entity.SimpleWebRequest <T> _request, CookieContainer cookie)
            where T : Entity.SimpleWebResponse
        {
            HttpResponse    httpResponse = null;
            HttpWebResponse response     = null;

            var request = CreateRequest(_request, ref cookie);

            try
            {
                if (_request.HttpMethod == Enum.HttpMethods.POST)
                {
                    if (_request.QueryBytes == null || _request.QueryBytes.Length == 0)
                    {
                        if (!string.IsNullOrWhiteSpace(_request.QueryString))
                        {
                            WriteRequestParas(request, _request.QueryString);
                        }
                    }
                    else
                    {
                        WriteRequestParas(request, _request.QueryBytes);
                    }
                }

                response = await request.GetResponseAsync() as HttpWebResponse;
            }
            catch (WebException ex)
            {
                response = ex.Response as HttpWebResponse;
            }

            httpResponse = new HttpResponse(response);
            var encoding = response.Headers["Content-Encoding"];

            using (Stream s = response.GetResponseStream())
            {
                if (!string.IsNullOrEmpty(encoding))
                {
                    if (encoding.ToLower().Contains("gzip"))
                    {
                        GZipStream st = new GZipStream(s, CompressionMode.Decompress);
                        httpResponse.ResponseBytes = ReadStreamBytes(st);
                    }
                    else if (encoding.ToLower().Contains("deflate"))
                    {
                        DeflateStream st = new DeflateStream(s, CompressionMode.Decompress);
                        httpResponse.ResponseBytes = ReadStreamBytes(st);
                    }
                }
                else
                {
                    httpResponse.ResponseBytes = ReadStreamBytes(s);
                }
            }

            response.Dispose();

            return(httpResponse);
        }
Beispiel #19
0
        public string GetString(HttpWebResponse response)
        {
            string strResult = "";

            try
            {
                Stream   receiveStream = response.GetResponseStream();
                string   encodeheader  = response.ContentType;
                Encoding encode        = _encoding;
                var      sr            = new StreamReader(receiveStream, encode);
                var      read          = new Char[256];
                int      count         = sr.Read(read, 0, 256);
                while (count > 0)
                {
                    var str = new String(read, 0, count);
                    strResult += str;
                    count      = sr.Read(read, 0, 256);
                }
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                    response.Dispose();
                }
            }
            return(strResult);
        }
Beispiel #20
0
        public static async Task <bool> VerifyNotify(string partner, string notifyId)
        {
            string url = "https://mapi.alipay.com/gateway.do?service=notify_verify&" + "partner=" + partner +
                         "&notify_id=" + notifyId;
            HttpWebRequest request = HttpWebRequest.CreateHttp(url);

            request.Timeout = 12000;
            try
            {
                HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync();

                Stream       stream = response.GetResponseStream();
                StreamReader reader = new StreamReader(stream);
                string       result = await reader.ReadToEndAsync();

                reader.Close();
                stream.Close();
                response.Dispose();
                return(result == "true");
            }
            catch
            {
                return(false);
            }
        }
Beispiel #21
0
    /// <summary>
    /// 获取网络文件大小
    /// </summary>
    /// <param name="url"></param>
    public static string GetWebFileSize(string url)
    {
        string result   = string.Empty;
        long   ContentL = 0;

        try
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.MaximumAutomaticRedirections = 4;
            request.MaximumResponseHeadersLength = 4;
            request.Credentials = CredentialCache.DefaultCredentials;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            ContentL = response.ContentLength;
            response.Close();
            response.Dispose();
            response = null;
            request  = null;
            // response.Server
            result = string.Format("大小: {0}", GetSize(ContentL));
        }
        catch (Exception ex)
        {
            result = string.Format("大小: {0}", "未知");
        }
        return(result);
    }
Beispiel #22
0
        //public Task<List<string>> GetIndividualUrlsAdsBetaTest()
        //{
        //    //div[@class='inner']/ul[1]
        //    //Транспорт имя
        //    //ul[@class='small suggestinput bgfff lheight20 br-3 abs subcategories binded']/li
        //    //дата валуе для запроса /list
        //    //ul[@class='small suggestinput bgfff lheight20 br-3 abs subcategories binded']/li/a/@data-value

        //    //Optimized поиск other link
        //    //ul/li[@class='hidden']/a/@href

        //    var htmlDocument = new HtmlAgilityPack.HtmlDocument();
        //    var parseIndividualAdsData = new List<string>();
        //    return Task.Run(() =>
        //    {
        //        for (int i = 0; i < ContentCollection.Count; i++)
        //        {
        //            htmlDocument.LoadHtml(ContentCollection[i]);
        //            //ul/li[@class='hidden']/a
        //            HtmlNodeCollection nodeIndividualAds = htmlDocument.DocumentNode.SelectNodes("//div[@class='inner']/ul/li/a");

        //            if (nodeIndividualAds != null)
        //            {
        //                for (var k = 0; k < nodeIndividualAds.Count; k++)
        //                {
        //                    IndividualAdsUrlsCollection.Add(nodeIndividualAds[k].Attributes["href"].Value);
        //                    parseIndividualAdsData.Add(nodeIndividualAds[k].Attributes["href"].Value);
        //                }
        //            }
        //        }
        //        return parseIndividualAdsData.Distinct().ToList();
        //    });
        //}
        #endregion

        public async Task GetUrlData(int cityId)
        {
            string         getHtml    = "";
            string         url        = "https://www.olx.kz/ajax/geo6/getstatsandlinks/";
            List <string>  getDataUrl = new List <string>();
            HttpWebRequest request    = WebRequest.Create(url) as HttpWebRequest;

            request.Method      = "POST";
            request.UserAgent   = "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36";
            request.ContentType = "application/x-www-form-urlencoded";
            string data = $"region_id=&city_id={cityId}&district_id=0&dist=0&onlylinks=1";

            byte[] getDataBytes = Encoding.UTF8.GetBytes(data);
            request.ContentLength = getDataBytes.Length;
            //CookieContainer cookieContainer = new CookieContainer();
            //  request.CookieContainer = cookieContainer;

            using (Stream stream = await request.GetRequestStreamAsync())
            {
                await stream.WriteAsync(getDataBytes, 0, getDataBytes.Length);
            }

            HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse;

            using (var stream = new StreamReader(response.GetResponseStream()))
            {
                getHtml = await stream.ReadToEndAsync();
            }
            response.Close();
            response.Dispose();
        }
Beispiel #23
0
        private void DownloadFile(DownloadInfo download)
        {
            if (!Directory.Exists(Path.GetDirectoryName(download.Path)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(download.Path));
            }

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(download.Url);
                request.Proxy     = null;
                request.KeepAlive = true;
                request.Method    = "GET";
                request.UserAgent = "Mozilla/5.0 (compatible; Windows NT 10.0; .NET CLR 4.0.30319;)";

                cts.Token.Register(() => request.Abort());
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;

                if (cts.IsCancellationRequested)
                {
                    return;
                }

                using (var fileStream = new FileStream(download.Path, FileMode.Create, FileAccess.Write))
                {
                    var    responseStream = response.GetResponseStream();
                    byte[] buffer         = new byte[bufferSize];
                    int    size           = responseStream.Read(buffer, 0, bufferSize);

                    while (!cts.IsCancellationRequested && size > 0)
                    {
                        fileStream.Write(buffer, 0, size);
                        size = responseStream.Read(buffer, 0, bufferSize);
                        Interlocked.Add(ref speed, size);
                    }
                    responseStream.Close();
                    response.Dispose();
                }
            }
            catch (WebException) when(cts.IsCancellationRequested)
            {
                File.Delete(download.Path);
                //你自己要取消的~
            }
            catch
            {
                System.Diagnostics.Debug.WriteLine(download.Url);
                Interlocked.Increment(ref failed);
                File.Delete(download.Path);
                return;
            }

            if (cts.IsCancellationRequested)
            {
                File.Delete(download.Path);
                return;
            }

            Interlocked.Increment(ref complete);
        }
        public static async Task <AnimeList> GetAnimeList(NetworkCredential credentials, string Username)
        {
            AnimeList       animeList = new AnimeList();
            HttpWebResponse response  = null;

            try
            {
                response = await SendHttpWebGETRequest(credentials, MAL_URL + "animelist/" + Username + "/load.json", ContentType.JSON);

                if (EnsureStatusCode(response))
                {
                    StreamReader responseStream   = new StreamReader(response.GetResponseStream());
                    string       responseAsString = responseStream.ReadToEnd();
                    animeList = JSONConverter.DeserializeJSon <AnimeList>(responseAsString);
                }
            }
            catch (WebException ex)
            {
                Debug.Write("GetAnimeList: WebException response: " + ex.Status);
            }
            finally
            {
                if (response != null)
                {
                    response.Dispose();
                }
            }
            return(animeList);
        }
        private static Exception ConvertWebException(WebException ex)
        {
            HttpWebResponse response = null;

            try
            {
                response = ex.Response as HttpWebResponse;
                if (response != null)
                {
                    string detail;
                    using (var reader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8))
                    {
                        detail = reader.ReadToEnd();
                    }

                    if (response.StatusCode == HttpStatusCode.NotFound)
                    {
                        return(new HttpNotFoundException(string.Concat("HTTP Resource Not Found: ", response.ResponseUri, "\r\n", detail)));
                    }
                    else
                    {
                        return(new ApplicationException(string.Concat("HTTP ERROR\r\n", detail)));
                    }
                }
                return(new ApplicationException("HTTP ERROR", ex));
            }
            finally
            {
                if (response != null)
                {
                    response.Dispose();
                    response = null;
                }
            }
        }
Beispiel #26
0
        internal static async Task CheckServerNetwork()
        {
            HttpWebRequest  request  = null;
            HttpWebResponse response = null;

            try
            {
                request        = WebRequest.Create(ETC.Server) as HttpWebRequest;
                request.Method = "HEAD";
                response       = request.GetResponse() as HttpWebResponse;

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    IsServerDown = false;
                }
                else
                {
                    IsServerDown = true;
                }
            }
            catch (Exception ex)
            {
                LogError(ex.ToString());
                IsServerDown = true;
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
                response.Dispose();
            }
        }
Beispiel #27
0
        public static ResultCodes IsDisposableEmail(string email)
        {
            try
            {
                var addr = new System.Net.Mail.MailAddress(email);
                if (addr.Address == email)
                {
                    HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://services.toxiicdev.net/tmc/check.php?email=" + email);
                    req.Method = "GET";

                    HttpWebResponse res   = (HttpWebResponse)req.GetResponse();
                    StreamReader    s     = new StreamReader(res.GetResponseStream());
                    string          reply = s.ReadToEnd();
                    s.Dispose();
                    res.Dispose();
                    if (reply.Length != 0)
                    {
                        int responseCode = int.Parse(GetValueFromJSON(reply, "result_code\":", "\""));

                        return((ResultCodes)responseCode);
                    }
                }
            }
            catch { }

            return(ResultCodes.Invalid);
        }
Beispiel #28
0
        private string[] TLDs()
        {
            List <string>   result = new List <string>();
            string          rawUrl = "https://github.com/umpirsky/tld-list/raw/master/data/en/tld.txt";
            HttpWebRequest  req    = (HttpWebRequest)WebRequest.Create(rawUrl);
            HttpWebResponse res    = (HttpWebResponse)req.GetResponse();
            StreamReader    reader = new StreamReader(res.GetResponseStream());

            while (!reader.EndOfStream)
            {
                string line = reader.ReadLine();
                if (line.Contains("("))
                {
                    result.Add(line.Split(new string[] { "(" }, StringSplitOptions.None)[1].Replace(")", "").Trim());
                }
            }
            res.Close();
            res.Dispose();

            if (result.Count > 0)
            {
                return(result.ToArray());
            }
            else
            {
                return(null);
            }
        }
Beispiel #29
0
        private string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
        {
            Stream       stream = null;
            StreamReader reader = null;

            try
            {
                // 以字符流的方式读取HTTP响应
                stream = rsp.GetResponseStream();
                reader = new StreamReader(stream, encoding);
                return(reader.ReadToEnd());
            }
            finally
            {
                // 释放资源
                if (reader != null)
                {
                    reader.Dispose();
                }
                if (stream != null)
                {
                    stream.Dispose();
                }
                if (rsp != null)
                {
                    rsp.Dispose();
                }
            }
        }
        /// <summary>
        /// Checks if the provided path points to a valid directory or file.
        /// </summary>
        /// <returns><c>true</c>, if the directory or file exists, <c>false</c> otherwise.</returns>
        /// <param name="url">The remote url of the directory or file.</param>
        private bool DoesRemoteDirectoryOrFileExist(string url)
        {
            string         cleanURL = url.Replace(Path.DirectorySeparatorChar, '/');
            HttpWebRequest request  = CreateHttpWebRequest(cleanURL, this.Config.GetRemoteUsername(), this.Config.GetRemotePassword());

            request.Method = WebRequestMethods.Http.Head;
            HttpWebResponse response = null;

            try
            {
                response = (HttpWebResponse)request.GetResponse();
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return(false);
                }
            }
            catch (WebException wex)
            {
                response = (HttpWebResponse)wex.Response;
                if (response.StatusCode == HttpStatusCode.NotFound)
                {
                    return(false);
                }
            }
            finally
            {
                response?.Dispose();
            }

            return(true);
        }