コード例 #1
0
        /// <summary>
        /// Starts an asynchronous operation to get include info.
        /// </summary>
        /// <param name="domainName"></param>
        /// <param name="callback"></param>
        /// <param name="userState"></param>
        /// <returns></returns>
        public static IAsyncResult BeginGetIncludeInfo(string domainName, AsyncCallback callback, object userState)
        {
            HttpWebRequest request = CreateNormalRequest(GetIncludeInfoQueryUri(domainName));
            AsyncResult <IHaosouIncludeInfo> result = new AsyncResult <IHaosouIncludeInfo>(callback, userState);

            NetworkRequestAsyncTimeout.RegisterRequest(request.BeginGetResponse((ar) => {
                IHaosouIncludeInfo info = null;
                Exception error         = null;
                byte[] buffer           = g_bufferManager.TakeBuffer(BUFFER_SIZE);

                try {
                    string content = null;
                    using (HttpWebResponse response = (HttpWebResponse)((HttpWebRequest)ar.AsyncState).EndGetResponse(ar)) {
                        content = response.GetResponseString(buffer);
                    }

                    info = new IncludeInfo {
                        IncludeCount = ParseIncludeCount(content),
                    };
                } catch (Exception ex) {
                    error = ex;
                } finally {
                    g_bufferManager.ReturnBuffer(buffer);
                }

                result.MarkCompleted(error, false, info);
            }, request), request, TIMEOUT);

            return(result);
        }
コード例 #2
0
ファイル: WebHelper.cs プロジェクト: xphter/Xphter.Framework
        /// <summary>
        /// Starts an asynchronous operation to get web site info.
        /// </summary>
        /// <param name="domainName"></param>
        /// <param name="callback"></param>
        /// <param name="userState"></param>
        /// <returns></returns>
        public static IAsyncResult BeginGetWebSiteInfo(string url, IWebProxy proxy, AsyncCallback callback, object userState)
        {
            HttpWebRequest             request = CreateGetWebSiteInfoRequest(url, proxy);
            AsyncResult <IWebSiteInfo> result  = new AsyncResult <IWebSiteInfo>(callback, userState);

            NetworkRequestAsyncTimeout.RegisterRequest(request.BeginGetResponse((ar) => {
                IWebSiteInfo info = null;
                Exception error   = null;
                byte[] buffer     = g_bufferManager.TakeBuffer(BUFFER_SIZE);

                try {
                    string content = null;
                    using (HttpWebResponse response = (HttpWebResponse)((HttpWebRequest)ar.AsyncState).EndGetResponse(ar)) {
                        content = response.GetResponseString(buffer);
                        info    = ParseWebSiteInfo(url, response, content);
                    }
                } catch (Exception ex) {
                    error = ex;
                } finally {
                    g_bufferManager.ReturnBuffer(buffer);
                }

                result.MarkCompleted(error, false, info);
            }, request), request, TIMEOUT);

            return(result);
        }
コード例 #3
0
        private AlibabaException GetAlibabaException(WebException webException)
        {
            AlibabaException alibabaException = null;

            byte[] buffer = this.m_bufferManager.TakeBuffer(BUFFER_POOL_ITEM_SIZE);

            try {
                using (HttpWebResponse response = (HttpWebResponse)webException.Response) {
                    if (response != null)
                    {
                        string content = response.GetResponseString(buffer);

                        ChinaAlibabaErrorInfo info = this.m_jsonSerializer.Deserialize <ChinaAlibabaErrorInfo>(content);
                        alibabaException = new AlibabaException(info.error_description ?? info.error_message, (int)response.StatusCode, webException);
                    }
                    else
                    {
                        alibabaException = new AlibabaException(webException.Message, 500, webException);
                    }
                }
            } catch (Exception ex) {
                alibabaException = new AlibabaException(string.Format("Error occurred when parse error response: {0}", ex.Message), 500, ex);
            } finally {
                this.m_bufferManager.ReturnBuffer(buffer);
            }

            return(alibabaException);
        }
コード例 #4
0
        /// <summary>
        /// Starts an asynchronous operation to get keyword rank.
        /// </summary>
        /// <param name="domainName"></param>
        /// <param name="callback"></param>
        /// <param name="userState"></param>
        /// <returns></returns>
        public static IAsyncResult BeginGetKeywordRank(string keyword, string domainName, AsyncCallback callback, object userState)
        {
            HttpWebRequest request = CreateNormalRequest(GetKeywordRankQueryUri(keyword));
            AsyncResult <IEnumerable <int> > result = new AsyncResult <IEnumerable <int> >(callback, userState);

            NetworkRequestAsyncTimeout.RegisterRequest(request.BeginGetResponse((ar) => {
                IEnumerable <int> rank = null;
                Exception error        = null;
                byte[] buffer          = g_bufferManager.TakeBuffer(BUFFER_SIZE);

                try {
                    string content = null;
                    using (HttpWebResponse response = (HttpWebResponse)((HttpWebRequest)ar.AsyncState).EndGetResponse(ar)) {
                        content = response.GetResponseString(buffer);
                    }

                    rank = ParseKeywordRank(content, domainName);
                } catch (Exception ex) {
                    error = ex;
                } finally {
                    g_bufferManager.ReturnBuffer(buffer);
                }

                result.MarkCompleted(error, false, rank);
            }, request), request, TIMEOUT);

            return(result);
        }
コード例 #5
0
ファイル: CouchDatabase.cs プロジェクト: kpisman/LoveSeat
        /// <summary>
        /// Using the bulk API for the loading of documents.
        /// </summary>
        /// <param name="docs"></param>
        /// <remarks>Here we assume you have either added the correct rev, id, or _deleted attribute to each document.  The response will indicate if there were any errors.
        /// Please note that the max_document_size configuration variable in CouchDB limits the maximum request size to CouchDB.</remarks>
        /// <returns>JSON of updated documents in the BulkDocumentResponse class.  </returns>
        public BulkDocumentResponses SaveDocuments(Documents docs, bool all_or_nothing)
        {
            string uri = databaseBaseUri + "/_bulk_docs";

            string data = Newtonsoft.Json.JsonConvert.SerializeObject(docs);

            if (all_or_nothing == true)
            {
                uri = uri + "?all_or_nothing=true";
            }

            HttpWebResponse resp = GetRequest(uri).Post().Json().Data(data).GetResponse();

            if (resp == null)
            {
                throw new System.Exception("Response returned null.");
            }

            if (resp.StatusCode != HttpStatusCode.Created)
            {
                throw new System.Exception("Response returned with a HTTP status code of " + resp.StatusCode + " - " + resp.StatusDescription);
            }

            // Get response
            string x = resp.GetResponseString();

            // Convert to Bulk response
            BulkDocumentResponses bulk = Newtonsoft.Json.JsonConvert.DeserializeObject <BulkDocumentResponses>(x);

            return(bulk);
        }
コード例 #6
0
        /// <summary>
        /// Starts an asynchronous operation to push urls to baidu.com.
        /// </summary>
        /// <param name="site"></param>
        /// <param name="token"></param>
        /// <param name="urls"></param>
        /// <param name="callback"></param>
        /// <param name="userState"></param>
        /// <returns></returns>
        public static IAsyncResult BeginPush(string site, string token, bool isOriginal, IEnumerable <string> urls, AsyncCallback callback, object userState)
        {
            HttpWebRequest request = CreatePushRequest(site, token, isOriginal);
            AsyncResult <IBaiduPushResult> result = new AsyncResult <IBaiduPushResult>(callback, userState);

            byte[] data = Encoding.UTF8.GetBytes(urls.StringJoin("\r\n"));
            request.ContentLength = data.Length;
            NetworkRequestAsyncTimeout.RegisterRequest(request.BeginGetRequestStream((streamResult) => {
                try {
                    using (Stream writer = ((HttpWebRequest)streamResult.AsyncState).EndGetRequestStream(streamResult)) {
                        writer.Write(data, 0, data.Length);
                    }
                } catch (Exception ex) {
                    result.MarkCompleted(ex, false, null);
                    return;
                }

                NetworkRequestAsyncTimeout.RegisterRequest(((HttpWebRequest)streamResult.AsyncState).BeginGetResponse((contentResult) => {
                    string content        = null;
                    Exception error       = null;
                    PushResult pushResult = null;
                    byte[] buffer         = g_bufferManager.TakeBuffer(BUFFER_SIZE);

                    try {
                        using (HttpWebResponse response = (HttpWebResponse)((HttpWebRequest)contentResult.AsyncState).EndGetResponse(contentResult)) {
                            if (!string.IsNullOrWhiteSpace(content = response.GetResponseString(buffer)))
                            {
                                pushResult = new JavaScriptSerializer().Deserialize <PushResult>(content);
                            }
                        }
                    } catch (WebException ex) {
                        try {
                            using (HttpWebResponse response = (HttpWebResponse)ex.Response) {
                                if (response != null)
                                {
                                    if (!string.IsNullOrWhiteSpace(content = response.GetResponseString(buffer)))
                                    {
                                        pushResult = new JavaScriptSerializer().Deserialize <PushResult>(content);
                                    }
                                }
                                else
                                {
                                    error = ex;
                                }
                            }
                        } catch {
                            error = ex;
                        }
                    } catch (Exception ex) {
                        error = ex;
                    } finally {
                        g_bufferManager.ReturnBuffer(buffer);
                    }

                    result.MarkCompleted(error, false, pushResult);
                }, request), request, TIMEOUT);
            }, request), request, TIMEOUT);

            return(result);
        }
コード例 #7
0
        public static CouchResponseObject GetJObject(this HttpWebResponse response)
        {
            var resp = new CouchResponseObject(JObject.Parse(response.GetResponseString()));

            resp.StatusCode = (int)response.StatusCode;
            return(resp);
        }
コード例 #8
0
ファイル: CouchResponse.cs プロジェクト: Almarida/couchdb
 public CouchResponse(HttpWebResponse response)
 {
     responseString    = response.GetResponseString();
     statusCode        = response.StatusCode;
     statusDescription = response.StatusDescription;
     etag = response.Headers["ETag"];
 }
コード例 #9
0
        public bool Like(string proxy = "")
        {
            if (!Helpers.Initialized || !Cookies.Authenticated)
            {
                return(false);
            }

            string         photoId = Helpers.GetPhotoId(PhotoUrl, proxy);
            HttpWebRequest request = WebRequest.Create($"https://www.instagram.com/web/likes/{photoId}/like/") as HttpWebRequest;

            if (proxy != string.Empty)
            {
                request.SetRequestProxy(proxy);
            }
            request.Method        = "POST";
            request.Host          = "www.instagram.com";
            request.KeepAlive     = true;
            request.ContentLength = 0;
            request.Headers.Add("Origin", "https://www.instagram.com");
            request.Headers.Add("X-Requested-With", "XMLHttpRequest");
            request.Headers.Add("X-Instagram-AJAX", "1");
            request.ContentType = "application/x-www-form-urlencoded";
            request.Accept      = "*/*";
            request.UserAgent   = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36";
            request.Headers.Add("X-CSRFToken", Cookies.Csrf);
            request.Referer = PhotoUrl;
            request.Headers.Add("Accept-Language", "en-US,en;q=0.8");
            request.Headers.Add($"Cookie: mid=WVQlEwALAAHqb7X4T62PaIWpf6tO; sessionid={Cookies.SessionId}; ig_vw=1440; ig_pr=1; csrftoken={Cookies.Csrf}; rur={Cookies.Rur}; ds_user_id={Cookies.DsUserId}");

            HttpWebResponse response       = request.GetResponse() as HttpWebResponse;
            string          responseString = response.GetResponseString();

            return(responseString.Contains("{\"status\": \"ok\"}"));
        }
コード例 #10
0
ファイル: HttpHelper.cs プロジェクト: xman01111/MrcCore
        /// <summary>
        /// 以 GET 方式发送 Http 请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="timeout"></param>
        /// <param name="naked"></param>
        /// <returns></returns>
        public static string Get(string url, int timeout, bool naked = false)
        {
            HttpWebRequest  request  = null;
            HttpWebResponse response = null;
            string          result   = null;

            request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.AllowAutoRedirect = false;
            request.Timeout           = timeout;
            request.Method            = "GET";

            if (naked == false)
            {
                request.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36";
            }

            response = (HttpWebResponse)request.GetResponse();

            using (response)
            {
                result = response.GetResponseString();
            }

            return(result);
        }
コード例 #11
0
ファイル: HttpHelper.cs プロジェクト: xman01111/MrcCore
        /// <summary>
        ///
        /// </summary>
        /// <param name="url"></param>
        /// <param name="requestBody"></param>
        /// <param name="timeout"></param>
        /// <param name="naked"></param>
        /// <returns></returns>
        public static string Post(string url, string requestBody, int timeout = 100000, bool naked = false)
        {
            string result = null;

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

            request.Method      = "POST";
            request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";

            if (naked == false)
            {
                request.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36";
            }

            if (requestBody != null)
            {
                byte[] data       = Encoding.UTF8.GetBytes(requestBody);
                Stream postStream = request.GetRequestStream();
                postStream.Write(data, 0, data.Length);
            }

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

            using (response)
            {
                result = response.GetResponseString();
            }

            return(result);
        }
コード例 #12
0
        public bool Authenticate(string proxy = "")
        {
            if (!Helpers.Initialized)
            {
                return(false);
            }

            if (Username != string.Empty && Password != string.Empty)
            {
                string         post    = $"username={UrlEncode(Username)}&password={Password}";
                HttpWebRequest request = WebRequest.Create("https://www.instagram.com/accounts/login/ajax/") as HttpWebRequest;
                if (proxy != string.Empty)
                {
                    request.SetRequestProxy(proxy);
                }

                request.Method    = "POST";
                request.Host      = "www.instagram.com";
                request.KeepAlive = true;
                request.Headers.Add("Origin", "https://www.instagram.com");
                request.Headers.Add("X-Requested-With", "XMLHttpRequest");
                request.Headers.Add("X-Instagram-AJAX", "1");
                request.ContentType = "application/x-www-form-urlencoded";
                request.Accept      = "*/*";
                request.UserAgent   = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36";
                request.Headers.Add("X-CSRFToken", Cookies.Csrf);
                request.Referer = "https://www.instagram.com/";
                request.Headers.Add("Accept-Language", "en-US,en;q=0.8");
                request.Headers.Add("Cookie", $"mid=WVQlEwALAAHqb7X4T62PaIWpf6tO; ig_vw=1440; ig_pr=1; rur={Cookies.Rur}; csrftoken={Cookies.Csrf}");

                byte[] data = Encoding.ASCII.GetBytes(post);
                request.ContentLength = data.Length;
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                    stream.Close();
                }

                HttpWebResponse response       = request.GetResponse() as HttpWebResponse;
                string          responseString = response.GetResponseString();
                if (responseString.Contains("\"authenticated\": true"))
                {
                    Cookies.SessionId     = response.GetCookie("sessionid");
                    Cookies.DsUserId      = Helpers.GetUserId(Username, proxy);
                    Cookies.Authenticated = true;
                    return(true);
                }
                else
                {
                    Cookies.Authenticated = false;
                    return(false);
                }
            }
            else
            {
                return(false);
            }
        }
コード例 #13
0
        /// <summary>
        /// Makes an HTTP POST request to an endpoint URI with the passed parameters and returns the response.
        /// </summary>
        /// <typeparam name="T">The strong type of the HTTP response we are deserializing.</typeparam>
        /// <param name="endpoint">The endpoint URI where to make the request to.</param>
        /// <param name="parameters">The query string parameters, if any.</param>
        /// <returns>The HTTP response, deserialized into the strong type <typeparamref name="T"/>.</returns>
        private T HttpPost <T>(string endpoint, string parameters) where T : class, IHttpResponse, new()
        {
            T      result;
            string responseText;

            try
            {
                byte[] bytes = Encoding.ASCII.GetBytes(parameters);

                WebRequest request = WebRequest.Create(endpoint);
                request.Timeout       = 300 * 1000;
                request.ContentType   = Shared.PostMimeType;
                request.Method        = Shared.PostMethod;
                request.ContentLength = bytes.Length;

                Stream stream = request.GetRequestStream();
                stream.Write(bytes, 0, bytes.Length);
                stream.Close();

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

                responseText = response.GetResponseString();

                string json = Utility.QueryStringToJson(responseText);
                result         = json.DeserializeJson <T>();
                result.Dynamic = json.DeserializeJson();
            }
            catch (WebException web)
            {
                result = new T();
                try
                {
                    WebResponse response = web.Response;
                    if (response.ContentType == Utility.JsonMimeType)
                    {
                        responseText     = response.GetResponseString();
                        result.Exception = new BridgeException(Error.AccessingApiEndpoint.FormatWith(endpoint), web);
                        result.Dynamic   = responseText.DeserializeJson();
                    }
                    else
                    {
                        result.Exception = new BridgeException(Error.AccessingApiEndpoint.FormatWith(endpoint), web);
                    }
                }
                catch (Exception e)
                {
                    result.Exception = new BridgeException(Error.ExceptionAccessingApiEndpoint.FormatWith(endpoint), e);
                }
            }

            return(result);
        }
コード例 #14
0
ファイル: IpHelper.cs プロジェクト: xphter/Xphter.Framework
        /// <summary>
        /// Parses the HTTP response of the specified HTTP request for GetLocation operation.
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        private static IEnumerable <string> ParseGetLocationResponse(HttpWebRequest request, HttpWebResponse response)
        {
            byte[] buffer = g_ipLocationBufferManager.TakeBuffer(1024);

            try {
                string content = response.GetResponseString(buffer);
                SinaLocationServiceReturnValue value = g_jsSerializer.Deserialize <SinaLocationServiceReturnValue>(content);
                return(new string[] { value.country, value.province, value.city, });
            } finally {
                g_ipLocationBufferManager.ReturnBuffer(buffer);
                response.Close();
                request.Abort();
            }
        }
コード例 #15
0
ファイル: WebHelper.cs プロジェクト: xphter/Xphter.Framework
        /// <summary>
        /// Gets web site info of the specified URL.
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static IWebSiteInfo GetWebSiteInfo(string url, IWebProxy proxy)
        {
            HttpWebRequest request = CreateGetWebSiteInfoRequest(url, proxy);

            byte[] buffer = g_bufferManager.TakeBuffer(BUFFER_SIZE);

            try {
                string content = null;
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
                    content = response.GetResponseString(buffer);
                    return(ParseWebSiteInfo(url, response, content));
                }
            } finally {
                g_bufferManager.ReturnBuffer(buffer);
            }
        }
コード例 #16
0
        /// <summary>
        /// Gets keyword rank of the specified domain name.
        /// </summary>
        /// <param name="domainName"></param>
        /// <returns></returns>
        public static IEnumerable <int> GetKeywordRank(string keyword, string domainName)
        {
            HttpWebRequest request = CreateNormalRequest(GetKeywordRankQueryUri(keyword));

            byte[] buffer = g_bufferManager.TakeBuffer(BUFFER_SIZE);

            try {
                string content = null;
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
                    content = response.GetResponseString(buffer);
                }

                return(ParseKeywordRank(content, domainName));
            } finally {
                g_bufferManager.ReturnBuffer(buffer);
            }
        }
コード例 #17
0
        /// <summary>
        /// Gets include info of the specified domain name.
        /// </summary>
        /// <param name="domainName"></param>
        /// <returns></returns>
        public static ISougouIncludeInfo GetIncludeInfo(string domainName)
        {
            HttpWebRequest request = CreateNormalRequest(GetIncludeInfoQueryUri(domainName));

            byte[] buffer = g_bufferManager.TakeBuffer(BUFFER_SIZE);

            try {
                string content = null;
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
                    content = response.GetResponseString(buffer);
                }

                return(ParseIncludeInfo(content));
            } finally {
                g_bufferManager.ReturnBuffer(buffer);
            }
        }
コード例 #18
0
        /// <summary>
        /// Push urls to baidu.com.
        /// </summary>
        /// <param name="site"></param>
        /// <param name="token"></param>
        /// <param name="urls"></param>
        /// <returns></returns>
        public static IBaiduPushResult Push(string site, string token, bool isOriginal, IEnumerable <string> urls)
        {
            string         content    = null;
            PushResult     pushResult = null;
            HttpWebRequest request    = CreatePushRequest(site, token, isOriginal);

            byte[] buffer = g_bufferManager.TakeBuffer(BUFFER_SIZE);

            byte[] data = Encoding.UTF8.GetBytes(urls.StringJoin("\r\n"));
            request.ContentLength = data.Length;
            try {
                using (Stream writer = request.GetRequestStream()) {
                    writer.Write(data, 0, data.Length);
                }
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
                    if (!string.IsNullOrWhiteSpace(content = response.GetResponseString(buffer)))
                    {
                        pushResult = new JavaScriptSerializer().Deserialize <PushResult>(content);
                    }
                }
            } catch (WebException ex) {
                try {
                    using (HttpWebResponse response = (HttpWebResponse)ex.Response) {
                        if (response != null)
                        {
                            if (!string.IsNullOrWhiteSpace(content = response.GetResponseString(buffer)))
                            {
                                pushResult = new JavaScriptSerializer().Deserialize <PushResult>(content);
                            }
                        }
                        else
                        {
                            throw ex;
                        }
                    }
                } catch {
                    throw ex;
                }
            } finally {
                g_bufferManager.ReturnBuffer(buffer);
            }

            return(pushResult);
        }
コード例 #19
0
        /// <summary>
        /// Begins an asynchronous operation to invoke the update notification service of baidu.com(Baidu PING).
        /// </summary>
        /// <param name="siteName"></param>
        /// <param name="homepageUri"></param>
        /// <param name="articleUri"></param>
        /// <param name="rssUri"></param>
        /// <param name="callback"></param>
        /// <param name="userState"></param>
        /// <returns></returns>
        public static IAsyncResult BeginPing(string siteName, string homepageUri, string articleUri, string rssUri, AsyncCallback callback, object userState)
        {
            HttpWebRequest     request = CreatePingRequest();
            AsyncResult <bool> result  = new AsyncResult <bool>(callback, userState);

            byte[] data = Encoding.UTF8.GetBytes(string.Format(g_pingRequestFormat, siteName, homepageUri, articleUri, rssUri));
            request.ContentLength = data.Length;
            NetworkRequestAsyncTimeout.RegisterRequest(request.BeginGetRequestStream((streamResult) => {
                try {
                    using (Stream writer = ((HttpWebRequest)streamResult.AsyncState).EndGetRequestStream(streamResult)) {
                        writer.Write(data, 0, data.Length);
                    }
                } catch (WebException) {
                    result.MarkCompleted(null, false, false);
                    return;
                } catch (Exception ex) {
                    result.MarkCompleted(ex, false, false);
                    return;
                }

                NetworkRequestAsyncTimeout.RegisterRequest(((HttpWebRequest)streamResult.AsyncState).BeginGetResponse((contentResult) => {
                    string content  = null;
                    Exception error = null;
                    byte[] buffer   = g_bufferManager.TakeBuffer(BUFFER_SIZE);

                    try {
                        using (HttpWebResponse response = (HttpWebResponse)((HttpWebRequest)contentResult.AsyncState).EndGetResponse(contentResult)) {
                            content = response.GetResponseString(buffer);
                        }
                    } catch (WebException) {
                    } catch (Exception ex) {
                        error = ex;
                    } finally {
                        g_bufferManager.ReturnBuffer(buffer);
                    }

                    result.MarkCompleted(error, false, !string.IsNullOrWhiteSpace(content) && content.Contains("<int>0</int>"));
                }, request), request, TIMEOUT);
            }, request), request, TIMEOUT);

            return(result);
        }
コード例 #20
0
        private void SendHttpRequest <TReturn>(HttpWebRequest request, Action <Exception, TReturn> callback) where TReturn : IWeChatReturnValue
        {
            Exception syncError = null;

            try {
                NetworkRequestAsyncTimeout.RegisterRequest(request.BeginGetResponse((ar) => {
                    string content  = null;
                    Exception error = null;
                    byte[] buffer   = this.m_bufferManager.TakeBuffer(BUFFER_POOL_ITEM_SIZE);

                    try {
                        using (HttpWebResponse response = (HttpWebResponse)((HttpWebRequest)ar.AsyncState).EndGetResponse(ar)) {
                            content = response.GetResponseString(Encoding.UTF8, buffer);
                        }
                    } catch (Exception ex) {
                        error = ex;
                    } finally {
                        this.m_bufferManager.ReturnBuffer(buffer);
                    }

                    TReturn value = default(TReturn);
                    if (error == null)
                    {
                        try {
                            value = WeChatReturnValue.Create <TReturn>(content);
                            error = this.DetectWeChatException(value);
                        } catch (Exception ex) {
                            error = ex;
                        }
                    }

                    callback(error, value);
                }, request), request, this.m_timeout);
            } catch (Exception ex) {
                syncError = ex;
            }

            if (syncError != null)
            {
                callback(syncError, default(TReturn));
            }
        }
コード例 #21
0
        public List <string> GetRecentPosts(int count = 3, string proxy = "")
        {
            //TODO: implement count.
            int c = Helpers.GetPostCount(Username);

            if (count > c)
            {
                count = c;
            }

            List <string> posts = new List <string>();

            if (!Helpers.Initialized || !Cookies.Authenticated)
            {
                return(null);
            }

            HttpWebRequest request = WebRequest.Create($"https://www.instagram.com/{Username}/") as HttpWebRequest;

            if (proxy != string.Empty)
            {
                request.SetRequestProxy(proxy);
            }
            request.Method    = "GET";
            request.KeepAlive = true;
            request.Headers.Add("Upgrade-Insecure-Requests", "1");
            request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36";
            request.Accept    = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8";
            request.Headers.Add("Accept-Language", "en-US,en;q=0.8");
            request.Headers.Add("Cookie", $"mid=WVQlEwALAAHqb7X4T62PaIWpf6tO; sessionid={Cookies.SessionId}; csrftoken={Cookies.Csrf}; ds_user_id={Cookies.DsUserId}; rur={Cookies.Rur}");

            HttpWebResponse response       = request.GetResponse() as HttpWebResponse;
            string          responseString = response.GetResponseString();
            string          pattern        = "\"code\": \"(.*?)\"";

            foreach (Match item in (new Regex(pattern).Matches(responseString)))
            {
                posts.Add($"https://www.instagram.com/p/{item.Groups[1].Value}/");
            }
            return(posts);
        }
コード例 #22
0
        public bool Follow(string proxy = "")
        {
            if (!Helpers.Initialized || !Cookies.Authenticated)
            {
                return(false);
            }

            string         post    = string.Empty;
            string         userId  = Helpers.GetUserId(Username, proxy);
            HttpWebRequest request = WebRequest.Create($"https://www.instagram.com/web/friendships/{userId}/follow/") as HttpWebRequest;

            if (proxy != string.Empty)
            {
                request.SetRequestProxy(proxy);
            }
            request.Method        = "POST";
            request.Host          = "www.instagram.com";
            request.KeepAlive     = true;
            request.ContentLength = 0;
            request.Headers.Add("Origin", "https://www.instagram.com");
            request.ContentType = "application/x-www-form-urlencoded";
            request.Accept      = "*/*";
            request.UserAgent   = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36";
            request.Headers.Add("X-CSRFToken", Cookies.Csrf);
            request.Referer = $"https://www.instagram.com/{Username}/";
            request.Headers.Add("Accept-Language", "en-US,en;q=0.8");
            request.Headers.Add("Cookie", $"mid=WVQlEwALAAHqb7X4T62PaIWpf6tO; sessionid={Cookies.SessionId}; ig_vw=1440; ig_pr=1; csrftoken={Cookies.Csrf}; rur={Cookies.Rur}; ds_user_id={Cookies.DsUserId}");

            HttpWebResponse response       = request.GetResponse() as HttpWebResponse;
            string          responseString = response.GetResponseString();

            if (responseString.Contains("following") || responseString.Contains("requested"))
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
コード例 #23
0
        private void SendHttpRequest(HttpWebRequest request, Action <Exception, string> callback)
        {
            NetworkRequestAsyncTimeout.RegisterRequest(request.BeginGetResponse((ar) => {
                string content  = null;
                Exception error = null;
                byte[] buffer   = this.m_bufferManager.TakeBuffer(BUFFER_POOL_ITEM_SIZE);

                try {
                    using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(ar)) {
                        content = response.GetResponseString(buffer);
                    }
                } catch (WebException ex) {
                    error = this.GetAlibabaException(ex);
                } catch (Exception ex) {
                    error = new AlibabaException(string.Format("Error occurred when send HTTP request: {0}", ex.Message), 500, ex);
                } finally {
                    this.m_bufferManager.ReturnBuffer(buffer);
                }

                callback(error, content);
            }, null), request, this.m_timeout);
        }
コード例 #24
0
        /// <summary>
        /// Invokes the update notification service of baidu.com(Baidu PING).
        /// </summary>
        /// <param name="siteName"></param>
        /// <param name="homepageUri"></param>
        /// <param name="articleUri"></param>
        /// <param name="rssUri"></param>
        /// <returns></returns>
        public static bool Ping(string siteName, string homepageUri, string articleUri, string rssUri)
        {
            string         content = null;
            HttpWebRequest request = CreatePingRequest();

            byte[] buffer = g_bufferManager.TakeBuffer(BUFFER_SIZE);

            byte[] data = Encoding.UTF8.GetBytes(string.Format(g_pingRequestFormat, siteName, homepageUri, articleUri, rssUri));
            request.ContentLength = data.Length;
            try {
                using (Stream writer = request.GetRequestStream()) {
                    writer.Write(data, 0, data.Length);
                }
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
                    content = response.GetResponseString(buffer);
                }
            } catch (WebException) {
            } finally {
                g_bufferManager.ReturnBuffer(buffer);
            }

            return(!string.IsNullOrWhiteSpace(content) && content.Contains("<int>0</int>"));
        }
コード例 #25
0
        public List <string> GetResults(string proxy = "")
        {
            if (!Helpers.Initialized || !Cookies.Authenticated)
            {
                return(null);
            }

            List <string> results = new List <string>();

            HttpWebRequest request = WebRequest.Create($"https://www.instagram.com/web/search/topsearch/?context=blended&query={Query}&rank_token=0.19220890817980907") as HttpWebRequest;

            if (proxy != string.Empty)
            {
                request.SetRequestProxy(proxy);
            }
            request.Method    = "GET";
            request.Host      = "www.instagram.com";
            request.KeepAlive = true;
            request.Accept    = "*/*";
            request.Headers.Add("X-Requested-With", "XMLHttpRequest");
            request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36";
            request.Referer   = "https://www.instagram.com/explore/people/";
            request.Headers.Add("Accept-Language", "en-US,en;q=0.8");
            request.Headers.Add("Cookie", $"mid=WVQlEwALAAHqb7X4T62PaIWpf6tO; sessionid={Cookies.SessionId}; ig_vw=1440; ig_pr=1; rur={Cookies.Rur}; csrftoken={Cookies.Csrf}; ds_user_id={Cookies.DsUserId}");

            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            string          result   = response.GetResponseString();

            dynamic json = JsonConvert.DeserializeObject(result);

            for (int i = 0; i < json.users.Count; i++)
            {
                results.Add(json.users[i].user.username.ToString());
            }

            return(results);
        }
コード例 #26
0
        public static Document GetCouchDocument(this HttpWebResponse response)
        {
            var jobj = JObject.Parse(response.GetResponseString());

            return(new Document(jobj));
        }
コード例 #27
0
 public static JObject GetJObject(this HttpWebResponse response)
 {
     return(JObject.Parse(response.GetResponseString()));
 }