Exemplo n.º 1
0
        static string HttpPost(string URI, string Parameters)
        {
            System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
            req.ContentType = "application/x-www-form-urlencoded";
            req.Method      = "POST";
            //We need to count how many bytes we're sending. Post'ed Faked Forms should be name=value&
            byte[] bytes = System.Text.Encoding.ASCII.GetBytes(Parameters.ToString());
            req.ContentLength = bytes.Length;
            System.IO.Stream os = null;
            try
            {
                os = req.GetRequestStream();
                os.Write(bytes, 0, bytes.Length);
                os.Close();
                System.Net.WebResponse resp = req.GetResponse();
                System.IO.StreamReader sr   = new System.IO.StreamReader(resp.GetResponseStream());

                string towritestring = sr.ReadToEnd().Trim();
                return(towritestring);
            }
            catch
            {
                return(null);
            }
        }
Exemplo n.º 2
0
        public static System.Net.WebRequest MakeRequest(string url, Dictionary <string, object> data, bool addCookieContainer = false)
        {
            System.Net.WebRequest request = System.Net.WebRequest.Create(url);
            request.ContentType = "application/x-www-form-urlencoded";
            request.Method      = "POST";

            if (addCookieContainer)
            {
                ((System.Net.HttpWebRequest)request).CookieContainer = new System.Net.CookieContainer();
            }

            StringBuilder parameter = new StringBuilder();

            foreach (var item in data)
            {
                parameter.AppendFormat("{0}={1}&", item.Key, item.Value);
            }

            byte[] bytes = System.Text.Encoding.ASCII.GetBytes(parameter.ToString().Trim('&'));
            request.ContentLength = bytes.Length;

            using (System.IO.Stream stream = request.GetRequestStream())
            {
                stream.Write(bytes, 0, bytes.Length); //Push data
                stream.Close();
            }

            return(request);
        }
Exemplo n.º 3
0
 public string POST(string Url, string Data)
 {
     try
     {
         System.Net.WebRequest req = System.Net.WebRequest.Create(Url);
         req.Method      = "POST";
         req.Timeout     = 100000;
         req.ContentType = "application/x-www-form-urlencoded";
         byte[] sentData = Encoding.GetEncoding(1251).GetBytes(Data);
         req.ContentLength = sentData.Length;
         System.IO.Stream sendStream = req.GetRequestStream();
         sendStream.Write(sentData, 0, sentData.Length);
         sendStream.Close();
         System.Net.WebResponse res           = req.GetResponse();
         System.IO.Stream       ReceiveStream = res.GetResponseStream();
         System.IO.StreamReader sr            = new System.IO.StreamReader(ReceiveStream, Encoding.UTF8);
         Char[] read  = new Char[256];
         int    count = sr.Read(read, 0, 256);
         string Out   = String.Empty;
         while (count > 0)
         {
             String str = new String(read, 0, count);
             Out  += str;
             count = sr.Read(read, 0, 256);
         }
         return(Out);
     } catch (System.Net.WebException) { return("-1"); }
 }
Exemplo n.º 4
0
        /*
         * public static void Post(string Data)
         * {
         *  System.Net.WebRequest reqPOST = System.Net.WebRequest.Create(@"http://www.onlinedengi.ru/dev/conclusion.php");
         *  reqPOST.Method = "POST";
         *  reqPOST.Timeout = 120000;
         *  reqPOST.ContentType = "application/x-www-form-urlencoded";
         *  byte[] sentData = Encoding.GetEncoding(1251).GetBytes(Data);
         *  reqPOST.ContentLength = sentData.Length;
         *
         *  System.IO.Stream sendStream = reqPOST.GetRequestStream();
         *  sendStream.Write(sentData, 0, sentData.Length);
         *  sendStream.Close();
         *
         *  System.Net.WebResponse respPOST = reqPOST.GetResponse();
         *  System.IO.Stream l_rcv_stream = respPOST.GetResponseStream();
         *
         *  System.IO.StreamReader l_sreader = new System.IO.StreamReader(l_rcv_stream, Encoding.GetEncoding(1251));
         *  string l_response = l_sreader.ReadToEnd();
         *  l_rcv_stream.Close();
         * }*/
        public static void Post(string WMZ)
        {
            string l_url = String.Format(@"http://passport.webmoney.ru/asp/VerifyWMID.asp?wmid={0}", WMZ);

            System.Net.WebRequest l_req = System.Net.WebRequest.Create(l_url);
            l_req.Method      = "POST";
            l_req.Timeout     = 120000;
            l_req.ContentType = "application/x-www-form-urlencoded";

            byte[] sentData = Encoding.GetEncoding(1251).GetBytes(WMZ);
            l_req.ContentLength = sentData.Length;

            System.IO.Stream sendStream = l_req.GetRequestStream();
            sendStream.Write(sentData, 0, sentData.Length);
            sendStream.Close();

            System.Net.WebResponse l_resp = l_req.GetResponse();
            string l_resp_q = l_resp.ResponseUri.Query;

            if (String.IsNullOrEmpty(l_resp_q))
            {
                string l_wmid = l_resp.ResponseUri.Query.Substring(6, 12);
            }
            ;
        }
Exemplo n.º 5
0
        private void PutDocument(string postUrl, string document)
        {
            byte[] data = new System.Text.ASCIIEncoding().GetBytes(document);

            System.Net.WebRequest request = System.Net.WebRequest.Create("request_string");
            request.UseDefaultCredentials = true;
            request.Credentials           = new System.Net.NetworkCredential("_username", "_password");
            request.Method        = "PUT";
            request.ContentType   = "text/json";
            request.ContentLength = data.Length;

            using (System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(request.GetRequestStream()))
            {
                try
                {
                    streamWriter.Write(document);
                    streamWriter.Flush();
                    streamWriter.Close();

                    System.Net.HttpWebResponse httpResponse = (System.Net.HttpWebResponse)request.GetResponse();
                    using (System.IO.StreamReader streamReader = new System.IO.StreamReader(httpResponse.GetResponseStream()))
                    {
                        string result = streamReader.ReadToEnd();
                        streamReader.Close();
                    }
                }
                catch (System.Exception e)
                {
                    //_logger.Error("Exception thrown when contacting service.", e);
                    //_logger.ErrorFormat("Error posting document to {0}", postUrl);
                }
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// The thread method that is invoked to perform the actual invocation,
        /// this ensures that we can abort the thread should we want to
        /// </summary>
        /// <param name="data">An object array with the required parameters. Index 0 is the System.Net.WebRequest, index 1 is the flag indicating if it should use GetRequestStream() or GetResponse(), index 2 is an empty slot for returning the result or an exception</param>
        private static void RunSafeGetRequest(object data)
        {
            object[] args = (object[])data;
            try
            {
                System.Net.WebRequest req = (System.Net.WebRequest)args[0];
                req.Timeout = System.Threading.Timeout.Infinite;

                bool getRequest = (bool)args[1];
                if (getRequest)
                {
                    args[2] = req.GetRequestStream();
                }
                else
                {
                    args[2] = req.GetResponse();
                }
            }
            catch (System.Threading.ThreadAbortException)
            {
            }
            catch (Exception ex)
            {
                args[2] = ex;
            }
        }
Exemplo n.º 7
0
        public void UpdateTableSchema(string datasetId, string tableName, string schemaJson)
        {
            System.Net.WebRequest request = System.Net.WebRequest.Create(string.Format(this.tableSchemaUri, datasetId, tableName)) as System.Net.HttpWebRequest;
            if (request != null)
            {
                request.Method        = "PUT";
                request.ContentLength = 0;
                request.ContentType   = "application/json";
                request.Headers.Add("Authorization", string.Format("Bearer {0}", this.authentication.AccessToken));

                byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(schemaJson);
                request.ContentLength = byteArray.Length;

                // Write JSON byte[] into a Stream
                using (Stream writer = request.GetRequestStream())
                {
                    writer.Write(byteArray, 0, byteArray.Length);
                }

                using (var response = request.GetResponse() as System.Net.HttpWebResponse)
                {
                    // Get reader from response stream
                    if (response != null)
                    {
                    }
                }
            }
        }
Exemplo n.º 8
0
        public static string httpPost(string address, string parameters)
        {
            string textResponse = string.Empty;

            try
            {
                System.Net.WebRequest request = System.Net.WebRequest.Create(address);
                request.ContentType = "application/x-www-form-urlencoded";
                request.Method      = "POST";
                byte[] bytes = System.Text.Encoding.ASCII.GetBytes(parameters);
                request.ContentLength = bytes.Length;

                System.IO.Stream os = request.GetRequestStream();
                os.Write(bytes, 0, bytes.Length);
                os.Close();

                System.Net.WebResponse response     = request.GetResponse();
                System.IO.StreamReader streamReader = new System.IO.StreamReader(response.GetResponseStream());
                textResponse = streamReader.ReadToEnd();
            }
            catch (Exception ex)
            {
                ErrorHandler.errorRaised(ex);
            }
            return(textResponse);
        }
Exemplo n.º 9
0
        string authorize()
        {
            string clientID     = "BodyArchitect";
            string clientSecret = "A+/n01Me7SlrW2V176LWJblB+KwDpHXoc3r1lr0qbzE=";

            String strTranslatorAccessURI = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";
            String strRequestDetails      = string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=http://api.microsofttranslator.com", Uri.EscapeDataString(clientID), Uri.EscapeDataString(clientSecret));

            System.Net.WebRequest webRequest = System.Net.WebRequest.Create(strTranslatorAccessURI);
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.Method      = "POST";

            byte[] bytes = System.Text.Encoding.ASCII.GetBytes(strRequestDetails);
            webRequest.ContentLength = bytes.Length;
            using (System.IO.Stream outputStream = webRequest.GetRequestStream())
            {
                outputStream.Write(bytes, 0, bytes.Length);
            }
            System.Net.WebResponse webResponse = webRequest.GetResponse();

            System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(AdmAccessToken));
            //Get deserialized object from JSON stream
            AdmAccessToken token = (AdmAccessToken)serializer.ReadObject(webResponse.GetResponseStream());

            return("Bearer " + token.access_token);
        }
Exemplo n.º 10
0
        private static string getAccessToken()
        {
            //1.

            string clientID     = "NotiQ1";
            string clientSecret = "lrOB6czlivrqK91fc2XmeRgDTrqf7mwO/NogL6OtNro=";

            String strTranslatorAccessURI = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";
            String strRequestDetails      = string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=http://api.microsofttranslator.com", HttpUtility.UrlEncode(clientID), HttpUtility.UrlEncode(clientSecret));

            System.Net.WebRequest webRequest = System.Net.WebRequest.Create(strTranslatorAccessURI);
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.Method      = "POST";

            byte[] bytes = System.Text.Encoding.ASCII.GetBytes(strRequestDetails);
            webRequest.ContentLength = bytes.Length;
            using (System.IO.Stream outputStream = webRequest.GetRequestStream())
            {
                outputStream.Write(bytes, 0, bytes.Length);
            }
            System.Net.WebResponse webResponse = webRequest.GetResponse();

            System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(AdmAccessToken));
            //Get deserialized object from JSON stream
            AdmAccessToken token = (AdmAccessToken)serializer.ReadObject(webResponse.GetResponseStream());

            //string headerValue = "Bearer " + token.access_token;

            return(token.access_token);
        }
Exemplo n.º 11
0
        private static string POST(string Url, string Data) // послать пост запрос и вернуть ответ
        {
            System.Net.WebRequest req = System.Net.WebRequest.Create(Url);
            req.Method      = "POST";
            req.Timeout     = 100000;
            req.ContentType = "application/x-www-form-urlencoded1";
            byte[] sentData = Encoding.GetEncoding("utf-8").GetBytes(Data);
            req.ContentLength = sentData.Length;
            System.IO.Stream sendStream = req.GetRequestStream();
            sendStream.Write(sentData, 0, sentData.Length);
            sendStream.Close();
            System.Net.WebResponse res           = req.GetResponse();
            System.IO.Stream       ReceiveStream = res.GetResponseStream();
            System.IO.StreamReader sr            = new System.IO.StreamReader(ReceiveStream, Encoding.UTF8);
            //Кодировка указывается в зависимости от кодировки ответа сервера
            Char[] read  = new Char[256];
            int    count = sr.Read(read, 0, 256);
            string Out   = String.Empty;

            while (count > 0)
            {
                String str = new String(read, 0, count);
                Out  += str;
                count = sr.Read(read, 0, 256);
            }
            return(Out);
        }
Exemplo n.º 12
0
        public static string SendYPSms(string mobile, string text)
        {
            //地址
            string BASE_URI = "http://yunpian.com";
            //服务版本号
            string VERSION = "v1";
            //通用接口发短信的http地址
            string URI_SEND_SMS = BASE_URI + "/" + VERSION + "/sms/send.json";
            var    ApiKey       = "df1d8e5907e24edac658ecc233223540";

            if (!string.IsNullOrEmpty(text) && !string.IsNullOrEmpty(mobile))
            {
                //注意:参数必须进行Uri.EscapeDataString编码。以免&#%=等特殊符号无法正常提交
                string parameter = "apikey=" + ApiKey + "&text=" + Uri.EscapeDataString(text) + "&mobile=" + mobile;
                var    extend    = Guid.NewGuid().ToString();
                //if (!string.IsNullOrEmpty(extend) && Regex.IsMatch(extend, @"^[a-zA-Z0-9]*?$"))
                parameter += "&extend" + extend;
                System.Net.WebRequest req = System.Net.WebRequest.Create(URI_SEND_SMS);
                req.ContentType = "application/x-www-form-urlencoded";
                req.Method      = "POST";
                byte[] bytes = System.Text.Encoding.UTF8.GetBytes(parameter);//这里编码设置为utf8
                req.ContentLength = bytes.Length;
                System.IO.Stream os = req.GetRequestStream();
                os.Write(bytes, 0, bytes.Length);
                os.Close();
                System.Net.WebResponse resp = req.GetResponse();
                if (resp != null)
                {
                    System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
                    var responseJson          = sr.ReadToEnd();
                }
                return("");
            }
            return("短信发送失败,手机号码或短信内容不能为空。");
        }
Exemplo n.º 13
0
        /* -------------------------------------------------------------------------------------
        * Name:        WebRequestPostData
        * Goal:        Post a web request and return the string data
        * Parameters:  url       - Address to use
        *              postData  - Input xml to be sent
        * History:
        * 1/feb/2016 ERK Created
        *  ------------------------------------------------------------------------------------- */
        private static string WebRequestPostData(string url, string postData)
        {
            System.Net.WebRequest req = System.Net.WebRequest.Create(url);

            req.ContentType = "text/xml";
            req.Method      = "POST";

            byte[] bytes = System.Text.Encoding.ASCII.GetBytes(postData);
            req.ContentLength = bytes.Length;

            using (Stream os = req.GetRequestStream()) {
                os.Write(bytes, 0, bytes.Length);
            }

            using (System.Net.WebResponse resp = req.GetResponse()) {
                if (resp == null)
                {
                    return(null);
                }

                using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream())) {
                    return(sr.ReadToEnd().Trim());
                }
            }
        }
Exemplo n.º 14
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="strEncoding"></param>
        /// <returns></returns>st
        public static string GetHtmlFromUrl(string Url, string strData, string strEncoding = "UTF-8")
        {
            try
            {
                ASCIIEncoding encoding = new ASCIIEncoding();
                byte[]        byte1    = Encoding.UTF8.GetBytes(strData);

                System.Net.WebRequest wReq = System.Net.WebRequest.Create(Url);
                wReq.Method      = "Post";
                wReq.ContentType = "application/x-www-form-urlencoded";

                System.IO.Stream newStream = wReq.GetRequestStream();
                newStream.Write(byte1, 0, byte1.Length);
                newStream.Close();


                // Get the response instance.
                System.Net.WebResponse wResp = wReq.GetResponse();



                System.IO.Stream respStream = wResp.GetResponseStream();
                // Dim reader As StreamReader = New StreamReader(respStream)
                using (System.IO.StreamReader reader = new System.IO.StreamReader(respStream, Encoding.GetEncoding(strEncoding)))
                {
                    return(reader.ReadToEnd());
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 15
0
        public static string HttpPost(string uri, string parameters, string token = "")
        {
            System.Net.WebRequest req = System.Net.WebRequest.Create(uri);

            //Add these, as we're doing a POST
            req.ContentType = "application/x-www-form-urlencoded";
            req.Method      = "POST";
            if (!string.IsNullOrEmpty(token))
            {
                req.Headers.Add("__RequestVerificationToken", token);
            }
            //We need to count how many bytes we're sending. Post'ed Faked Forms should be name=value&
            byte[] bytes = System.Text.Encoding.ASCII.GetBytes(parameters);
            req.ContentLength = bytes.Length;

            System.IO.Stream os = req.GetRequestStream();
            os.Write(bytes, 0, bytes.Length); //Push it out there
            os.Close();

            System.Net.WebResponse resp = req.GetResponse();
            if (resp == null)
            {
                return(null);
            }
            System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
            return(sr.ReadToEnd().Trim());
        }
Exemplo n.º 16
0
        bool CheckForHFT()
        {
            bool success = false;

            try {
                System.Net.WebRequest request = System.Net.WebRequest.Create(m_gameServer.GetBaseHttpUrl());
                request.Method = "POST";
                string postData  = "{\"cmd\":\"happyFunTimesPing\"}";
                byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(postData);
                request.ContentType   = "application/json";
                request.ContentLength = byteArray.Length;
                Stream dataStream = request.GetRequestStream();
                dataStream.Write(byteArray, 0, byteArray.Length);
                dataStream.Close();
                System.Net.WebResponse response = request.GetResponse();
                dataStream = response.GetResponseStream();
                StreamReader reader             = new StreamReader(dataStream);
                string       responseFromServer = reader.ReadToEnd();
                reader.Close();
                dataStream.Close();
                response.Close();
                success = responseFromServer.Contains("HappyFunTimes");
                if (success)
                {
                    Debug.Log("HappyFunTimes found");
                }
            } catch (System.Exception) {
                Debug.Log("waiting for happyfuntimes...");
            }
            return(success);
        }
Exemplo n.º 17
0
        public static string Post(string URI, string Parameters)
        {
            try
            {
                System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
                //req.Proxy = new System.Net.WebProxy(ProxyString, true);

                req.ContentType = "application/x-www-form-urlencoded";
                req.Method      = "POST";

                byte[] bytes = System.Text.Encoding.ASCII.GetBytes(Parameters);
                req.ContentLength = bytes.Length;

                System.IO.Stream os = req.GetRequestStream();
                os.Write(bytes, 0, bytes.Length);
                os.Close();

                System.Net.WebResponse resp = req.GetResponse();
                if (resp == null)
                {
                    return(null);
                }
                System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
                return(sr.ReadToEnd().Trim());
            }
            catch (Exception e)
            {
                return("");
            }
        }
        private TokenResponse AcquireAccessToken(string PostBody, string EndPointUrl)
        {
            TokenResponse result = null;

            System.Net.WebRequest request = System.Net.WebRequest.Create(EndPointUrl);

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

            try
            {
                using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                {
                    streamWriter.Write(PostBody);
                    streamWriter.Flush();
                    streamWriter.Close();
                }

                System.Net.WebResponse response = request.GetResponse();
                using (Stream responseStream = response.GetResponseStream())
                {
                    StreamReader reader       = new StreamReader(responseStream, Encoding.Default);
                    string       jsonResponse = reader.ReadToEnd();

                    // Deserialize and get an Access Token.
                    result = Deserialize <TokenResponse>(jsonResponse);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\r\n\r\n" + ex.StackTrace, "Office365APIEditor");
            }

            return(result);
        }
Exemplo n.º 19
0
        public string GetID(string PathTorrent, string ServerAdress)
        {
            System.Net.WebClient WC = new System.Net.WebClient();
            WC.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0");
            WC.Encoding = System.Text.Encoding.UTF8;
            byte[] FileTorrent = WC.DownloadData(PathTorrent);

            string FileTorrentString = System.Convert.ToBase64String(FileTorrent);

            FileTorrent = System.Text.Encoding.Default.GetBytes(FileTorrentString);

            System.Net.WebRequest request = System.Net.WebRequest.Create("http://api.torrentstream.net/upload/raw");
            request.Method        = "POST";
            request.ContentType   = "application/octet-stream\\r\\n";
            request.ContentLength = FileTorrent.Length;
            System.IO.Stream dataStream = request.GetRequestStream();
            dataStream.Write(FileTorrent, 0, FileTorrent.Length);
            dataStream.Close();

            System.Net.WebResponse response = request.GetResponse();
            dataStream = response.GetResponseStream();
            System.IO.StreamReader reader = new System.IO.StreamReader(dataStream);
            string responseFromServer     = reader.ReadToEnd();

            string[] responseSplit = responseFromServer.Split('\"');
            return(responseSplit[3]);
        }
Exemplo n.º 20
0
        /// <summary>
        /// Sendet die Abfrage zum Server
        /// </summary>
        /// <returns></returns>
        public String SendRequest()
        {
            // Parameter
            byte[] bytes = Encoding.UTF8.GetBytes(this.GetRequestCommand());
            System.Net.WebRequest request = System.Net.WebRequest.Create(this.RequestAdress);
            request.Method        = "POST";
            request.ContentType   = this.ContentType;
            request.ContentLength = bytes.Length;

            // Ausgangs Stream
            System.IO.Stream reqStr = request.GetRequestStream();
            reqStr.Write(bytes, 0, bytes.Length);
            reqStr.Close();
            reqStr.Flush();

            // Antwort Stream
            System.Net.WebResponse response = request.GetResponse();
            System.IO.Stream       resStr   = response.GetResponseStream();
            System.IO.StreamReader reader   = new System.IO.StreamReader(resStr);
            String ResponseString           = reader.ReadToEnd();

            reader.Close();
            resStr.Close();
            response.Close();

            return(ResponseString);
        }
Exemplo n.º 21
0
        /// <summary>
        /// HttpPostでAccessTokenを取得する
        /// </summary>
        /// <param name="datamarketAccessUri"></param>
        /// <param name="requestDetails"></param>
        /// <returns></returns>
        private AdmAccessToken HttpPost(string requestDetails)
        {
            System.Net.WebRequest webRequest = System.Net.WebRequest.Create(DatamarketAccessUri);

            webRequest.ContentType = @"application/x-www-form-urlencoded";
            webRequest.Method      = @"POST";

            byte[] bytes = System.Text.Encoding.ASCII.GetBytes(requestDetails);

            webRequest.ContentLength = bytes.Length;

            using (System.IO.Stream outputStream = webRequest.GetRequestStream())
            {
                outputStream.Write(bytes, 0, bytes.Length);
            }

            using (System.Net.WebResponse webResponse = webRequest.GetResponse())
            {
                var serializer = new DataContractJsonSerializer(typeof(AdmAccessToken));

                //Get deserialized object from JSON stream
                AdmAccessToken token = (AdmAccessToken)serializer.ReadObject(webResponse.GetResponseStream());
                return(token);
            }
        }
Exemplo n.º 22
0
        public PluginApi.Plugins.Playlist SearchListRuTr(IPluginContext context, string search)
        {
            //Dim Kino As String = "100,101,1105,1165,1213,1235,124,1245,1246,1247,1248,1250,1386,1387,1388,1389,1390,1391,1478,1543,1576,1577,1642,1666,1670,185,187,1900,1991,208,209,2090,2091,2092,2093,2097,2109,212,2198,2199,22,2200,2201,2220,2221,2258,2339,2343,2365,2459,2491,2540,281,282,312,313,33,352,376,4,404,484,505,511,514,521,539,549,572,599,656,7,709,822,893,905,921,922,923,924,925,926,927,928,93,930,934,941"
            //Dim Dokumentals As String = ",103,1114,113,114,115,1186,1278,1280,1281,1327,1332,137,1453,1467,1468,1469,1475,1481,1482,1484,1485,1495,1569,1959,2076,2107,2110,2112,2123,2159,2160,2163,2164,2166,2168,2169,2176,2177,2178,2323,2380,24,249,251,2537,2538,294,314,373,393,46,500,532,552,56,670,671,672,752,821,827,851,876,882,939,97,979,98"
            //Dim Sport As String = ",1188,126,1287,1319,1323,1326,1343,1470,1491,1527,1551,1608,1610,1613,1614,1615,1616,1617,1620,1621,1623,1630,1667,1668,1675,1697,1952,1986,1987,1997,1998,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2014,2069,2073,2075,2079,2111,2124,2171,2425,2514,255,256,257,259,260,262,263,283,343,486,528,550,626,660,751,845,854,875,978"
            //Dim RequestPost As System.Net.WebRequest = System.Net.WebRequest.Create(TrackerServer & "/forum/tracker.php?f=" & Kino & Dokumentals & Sport & "&nm=" & search)
            System.Net.WebRequest RequestPost = System.Net.WebRequest.Create(TrackerServer + "/forum/tracker.php?nm=" + search);

            if (ProxyEnablerRuTr == true)
            {
                RequestPost.Proxy = new System.Net.WebProxy(ProxyServr, ProxyPort);
            }
            RequestPost.Method      = "POST";
            RequestPost.ContentType = "text/html; charset=windows-1251";
            RequestPost.Headers.Add("Cookie", Cookies);
            RequestPost.ContentType = "application/x-www-form-urlencoded";
            System.IO.Stream myStream = RequestPost.GetRequestStream();
            string           DataStr  = "prev_new=0&prev_oop=0&o=10&s=2&pn=&nm=" + search;

            byte[] DataByte = System.Text.Encoding.GetEncoding(1251).GetBytes(DataStr);
            myStream.Write(DataByte, 0, DataByte.Length);
            myStream.Close();

            System.Net.WebResponse Response   = RequestPost.GetResponse();
            System.IO.Stream       dataStream = Response.GetResponseStream();
            System.IO.StreamReader reader     = new System.IO.StreamReader(dataStream, System.Text.Encoding.GetEncoding(1251));
            string ResponseFromServer         = reader.ReadToEnd();


            System.Collections.Generic.List <Item>         items  = new System.Collections.Generic.List <Item>();
            System.Text.RegularExpressions.Regex           Regex  = new System.Text.RegularExpressions.Regex("(<tr class=\"tCenter hl-tr\">).*?(</tr>)");
            System.Text.RegularExpressions.MatchCollection Result = Regex.Matches(ResponseFromServer.Replace("\n", " "));

            if (Result.Count > 0)
            {
                foreach (System.Text.RegularExpressions.Match Match in Result)
                {
                    Item Item = new Item();
                    Regex = new System.Text.RegularExpressions.Regex("(?<=<a data-topic_id=\").*?(?=\")");
                    string LinkID = Regex.Matches(Match.Value)[0].Value;
                    Item.Link        = TrackerServer + "/forum/viewtopic.php?t=" + LinkID + ";PAGEFILMRUTR";
                    Regex            = new System.Text.RegularExpressions.Regex("(?<=" + LinkID + "\">).*?(?=</a>)");
                    Item.Name        = Regex.Matches(Match.Value)[0].Value;
                    Item.ImageLink   = "http://s1.iconbird.com/ico/1012/AmpolaIcons/w256h2561350597291utorrent2.png";
                    Item.Description = GetDescriptionSearhRuTr(Match.Value, Item.Name, LinkID);
                    items.Add(Item);
                }
            }
            else
            {
                Item Item = new Item();
                Item.Name = "Ничего не найдено";
                Item.Link = "";

                items.Add(Item);
            }

            return(PlayListPlugPar(items, context));
        }
Exemplo n.º 23
0
        private void button1_Click(object sender, EventArgs e)
        {
            System.Net.WebRequest r = null;
            try
            {
                r = System.Net.WebRequest.Create(textBox1.Text);
            }catch (Exception cv)
            {
                textBox2.Text = cv.Message;
                return;
            }
            r.ContentType = "text/xml";
            //r.Headers.Add("Content-Type:  application/soap+xml; charset=utf-8");
            //r.Headers.Add("Content-Length:  " + textBox2.Text.Length.ToString());
            r.Method = "POST";
            if (!String.IsNullOrWhiteSpace(textBox4.Text))
            {
                r.Headers.Add("SOAPAction: \"" + textBox4.Text + "\"");
            }
            System.IO.Stream       reqstream = r.GetRequestStream();
            System.IO.StreamWriter sw        = new System.IO.StreamWriter(reqstream);
            sw.Write(textBox2.Text);
            sw.Flush();
            try
            {
                //r.ContentLength = textBox2.Text.Length; //reqstream.Position;
                System.Net.WebResponse resp = r.GetResponse();

                System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
                textBox3.Text = sr.ReadToEnd();
                sr.Dispose();
                resp.Dispose();
            }
            catch (Exception ext)
            {
                textBox3.Text  = ext.Message + "\r\n" + ext.StackTrace;
                textBox3.Text += "\r\n";
                if (ext is System.Net.WebException)
                {
                    System.Net.WebException webex = (System.Net.WebException)ext;
                    try
                    {
                        using (System.IO.StreamReader exceptionreader = new System.IO.StreamReader(webex.Response.GetResponseStream()))
                        {
                            textBox3.Text += exceptionreader.ReadToEnd();
                        }
                    }catch (Exception ffff)
                    {
                        textBox3.Text += "\r\n Unknown Error trying to read response from Server";
                    }
                }
            }
            finally
            {
                sw.Dispose();
            }
            tabControl1.SelectedTab = tabPage2;
        }
Exemplo n.º 24
0
        private TokenResponse AcquireAccessTokenOfWebApp(string AuthorizationCode)
        {
            TokenResponse result      = null;
            string        accessToken = "";

            // Build a POST body.
            string    postBody  = "";
            Hashtable tempTable = new Hashtable();

            tempTable["grant_type"]    = "authorization_code";
            tempTable["code"]          = AuthorizationCode;
            tempTable["redirect_uri"]  = textBox_WebAppRedirectUri.Text;
            tempTable["client_id"]     = textBox_WebAppClientID.Text;
            tempTable["client_secret"] = textBox_WebAppClientSecret.Text;

            foreach (string key in tempTable.Keys)
            {
                postBody += String.Format("{0}={1}&", key, tempTable[key]);
            }
            byte[] postDataBytes = Encoding.ASCII.GetBytes(postBody);

            // This URL is old.
            // System.Net.WebRequest request = System.Net.WebRequest.Create("https://login.windows.net/common/oauth2/token/");

            // So, use new one. (access point is same.)
            System.Net.WebRequest request = System.Net.WebRequest.Create("https://login.microsoftonline.com/common/oauth2/token");

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

            try
            {
                // Get a RequestStream to POST a data.
                using (Stream reqestStream = request.GetRequestStream())
                {
                    reqestStream.Write(postDataBytes, 0, postDataBytes.Length);
                }

                System.Net.WebResponse response = request.GetResponse();
                using (Stream responseStream = response.GetResponseStream())
                {
                    StreamReader reader       = new StreamReader(responseStream, Encoding.Default);
                    string       jsonResponse = reader.ReadToEnd();

                    // Deserialize and get an Access Token.
                    result      = Deserialize <TokenResponse>(jsonResponse);
                    accessToken = result.access_token;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\r\n\r\n" + ex.StackTrace, "Office365APIEditor");
            }

            return(result);
        }
Exemplo n.º 25
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="biz_Content"> 参数如,发送短信的电话与发送类型new {PhoneNo="128888888",SendType=1}</param>
        /// <param name="actionPath">action地址"/api/AliyunSTK/Send"</param>
        public static (bool, string) Send(object biz_Content, string actionPath, Dictionary <string, string> headersDic = null)
        {
            DateTime DateStart = new DateTime(1970, 1, 1, 8, 0, 0);
            Dictionary <String, String> DicParameters = new Dictionary <String, String>();

            DicParameters.Add("apiKey", SDKOptions.ApiKey);
            DicParameters.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//时间戳

            string url = SDKOptions.Url + actionPath;

            DicParameters.Add("biz_content", JsonConvert.SerializeObject(biz_Content));
            DicParameters.Add("v", "1.0");
            string sign = Signature(DicParameters, SDKOptions.PrivateKey);//生成验签

            DicParameters.Add("sign", sign);
            System.Net.WebRequest wReq = System.Net.WebRequest.Create(SDKOptions.Url + actionPath);
            wReq.ContentType = "application/json";
            wReq.Method      = "POST";
            string postdata = JsonConvert.SerializeObject(DicParameters);

            if (headersDic != null)
            {
                foreach (KeyValuePair <string, string> kv in headersDic)
                {
                    wReq.Headers.Add(kv.Key, kv.Value);
                }
            }


            byte[] bytes     = Encoding.UTF8.GetBytes(postdata);
            string exMsg     = null;
            string reslutMsg = null;

            try
            {
                using (Stream sendStream = wReq.GetRequestStream())
                {
                    sendStream.Write(bytes, 0, bytes.Length);
                }
                System.Net.WebResponse wResp      = wReq.GetResponse();
                System.IO.Stream       respStream = wResp.GetResponseStream();
                using (System.IO.StreamReader reader = new System.IO.StreamReader(respStream, Encoding.GetEncoding("utf-8")))
                {
                    reslutMsg = reader.ReadToEnd();
                    return(true, reslutMsg);
                }
            }
            catch (Exception ex)
            {
                exMsg = ex.Message + ex.StackTrace + ex.Source;
                return(false, ex.Message);
            }
        }
Exemplo n.º 26
0
        /// <summary>
        /// Realiza la petición utilizando el método POST y devuelve la respuesta del servidor
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        /// <author>Findemor http://findemor.porExpertos.es</author>
        /// <history>Creado 17/02/2012</history>
        public static string GetResponse_POST(string url, Dictionary <string, string> parameters, string contentType, string user, string pass)
        {
            try
            {
                //Concatenamos los parametros, OJO: NO se añade el caracter "?"
                string parametrosConcatenados = ConcatParams(parameters);

                System.Net.WebRequest wr = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
                wr.Method = "POST";

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

                System.IO.Stream newStream;
                //Codificación del mensaje
                System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
                byte[] byte1 = encoding.GetBytes(parametrosConcatenados);
                wr.ContentLength = byte1.Length;
                wr.Headers.Add("Pxp-User", user);
                wr.Headers.Add("Php-Auth-User", user);
                wr.Headers.Add("Php-Auth-Pw", pass);
                //Envio de parametros
                newStream = wr.GetRequestStream();
                newStream.Write(byte1, 0, byte1.Length);

                // Obtiene la respuesta
                System.Net.WebResponse response = wr.GetResponse();
                // Stream con el contenido recibido del servidor
                newStream = response.GetResponseStream();
                System.IO.StreamReader reader = new System.IO.StreamReader(newStream);
                // Leemos el contenido
                string responseFromServer = reader.ReadToEnd();

                // Cerramos los streams
                reader.Close();
                newStream.Close();
                response.Close();
                return(responseFromServer);
            }
            catch (Exception ex)
            {
                if (ex.HResult == 404)
                {
                    throw new Exception("Not found remote service " + url);
                }
                else
                {
                    throw ex;
                }
            }
        }
Exemplo n.º 27
0
        private bool PostString(Uri target, string data, out string err)
        {
            err = null;
            //文字コードを指定する
            System.Text.Encoding enc = Encoding.Unicode;

            //POST送信する文字列を作成
            string postData = "error=" + Uri.EscapeDataString(data);

            //バイト型配列に変換
            byte[] postDataBytes = System.Text.Encoding.ASCII.GetBytes(postData);

            //WebRequestの作成
            System.Net.WebRequest req = System.Net.WebRequest.Create(target);

            req.Proxy = System.Net.WebRequest.DefaultWebProxy;

            //メソッドにPOSTを指定
            req.Method = "POST";
            //ContentTypeを"application/x-www-form-urlencoded"にする
            req.ContentType = "application/x-www-form-urlencoded";
            //POST送信するデータの長さを指定
            req.ContentLength = postDataBytes.Length;

            try
            {
                //データをPOST送信するためのStreamを取得
                System.IO.Stream reqStream = req.GetRequestStream();
                //送信するデータを書き込む
                reqStream.Write(postDataBytes, 0, postDataBytes.Length);
                reqStream.Close();

                //サーバーからの応答を受信するためのWebResponseを取得
                System.Net.WebResponse res = req.GetResponse();
                //応答データを受信するためのStreamを取得
                System.IO.Stream resStream = res.GetResponseStream();
                //受信して表示
                System.IO.StreamReader sr = new System.IO.StreamReader(resStream, enc);
                //閉じる
                sr.Close();
            }
            catch (Exception ex)
            {
                err = ex.Message;
                return(false);
            }
            return(true);
        }
Exemplo n.º 28
0
    public Client()
    {
        _webRequest        = System.Net.WebRequest.Create("some url");
        _webRequest.Method = "POST";

        const string keepAliveMessage = "{\"message\": {\"type\": \"keepalive\"}}";

        var keepAlives =
            from n in Observable.Interval(TimeSpan.FromSeconds(10.0))
            from u in Observable.Using(
                () => new StreamWriter(_webRequest.GetRequestStream()),
                sw => Observable.FromAsync(() => sw.WriteLineAsync(keepAliveMessage)))
            select u;

        _subscription = keepAlives.Subscribe();
    }
Exemplo n.º 29
0
        public void POST_Traid(string instr, string categories)
        {
            /*NameValueCollection Investing;
             * Investing = ConfigurationManager.GetSection("appSettings_API_Libertex") as NameValueCollection;
             * string url = Investing.Get("API");
             *
             * Investing = ConfigurationManager.GetSection(categories) as NameValueCollection;
             *
             * string url_ref = Investing.Get(instr);
             * url_ref = Regex.Replace(url_ref, "https://app.libertex.org/products/", "");
             * url_ref = Regex.Replace(url_ref, "agriculture/", "");
             * url_ref = Regex.Replace(url_ref, "currency/", "");
             * url_ref = Regex.Replace(url_ref, "crypto/", "");
             * url_ref = Regex.Replace(url_ref, "indexes/", "");
             * url_ref = Regex.Replace(url_ref, "energetics/", "");
             * url_ref = Regex.Replace(url_ref, "metal/", "");
             * url_ref = Regex.Replace(url_ref, "stock/", "");
             * url_ref = Regex.Replace(url_ref, "etf/", "");
             * url_ref = Regex.Replace(url_ref, "/", "");
             * MessageBox.Show(url_ref);*/


            string ProxyString = "";
            string URI         = @"https://app.libertex.org/spa/investing/open-position";;
            string Parameters  = "symbol=USDSEK&sumInv=50&mult=5&direction=reduction&number=12318195401&rate=9.275139999999999&spread=0.0038299999999999996&time=1561731033000" +
                                 "&isAutoIncreaseEnabled=0&csrfToken=3f1e3d4953a0dafce50d9df780002c55-99a786c105f3ce28216311484c8e45aa";

            System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
            //req.Proxy = new System.Net.WebProxy(ProxyString, true);
            req.ContentType = "application/json";
            req.Method      = "POST";
            //byte[] bytes = System.Text.Encoding.ASCII.GetBytes(Parameters);
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(Parameters);
            req.ContentLength = bytes.Length;
            System.IO.Stream os = req.GetRequestStream(); // создаем поток
            os.Write(bytes, 0, bytes.Length);             // отправляем в сокет
            os.Close();
            System.Net.WebResponse resp = req.GetResponse();
            if (resp == null)
            {
                MessageBox.Show("Что то ответ пустой");
                return;
            }
            System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
            MessageBox.Show(sr.ReadToEnd().Trim());
        }
Exemplo n.º 30
0
        /// <summary>
        /// http://blogs.msdn.com/b/translation/p/gettingstarted2.aspx
        /// </summary>
        private static void sample_usage()
        {
            //1.

            string clientID     = "NotiQ1";
            string clientSecret = "lrOB6czlivrqK91fc2XmeRgDTrqf7mwO/NogL6OtNro=";

            String strTranslatorAccessURI = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";
            String strRequestDetails      = string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=http://api.microsofttranslator.com", HttpUtility.UrlEncode(clientID), HttpUtility.UrlEncode(clientSecret));

            System.Net.WebRequest webRequest = System.Net.WebRequest.Create(strTranslatorAccessURI);
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.Method      = "POST";

            byte[] bytes = System.Text.Encoding.ASCII.GetBytes(strRequestDetails);
            webRequest.ContentLength = bytes.Length;
            using (System.IO.Stream outputStream = webRequest.GetRequestStream())
            {
                outputStream.Write(bytes, 0, bytes.Length);
            }
            System.Net.WebResponse webResponse = webRequest.GetResponse();

            System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(AdmAccessToken));
            //Get deserialized object from JSON stream
            AdmAccessToken token = (AdmAccessToken)serializer.ReadObject(webResponse.GetResponseStream());

            string headerValue = "Bearer " + token.access_token;


            //2.

            string txtToTranslate = "awesome";
            string uri            = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + System.Web.HttpUtility.UrlEncode(txtToTranslate) + "&from=en&to=pl";

            System.Net.WebRequest translationWebRequest = System.Net.WebRequest.Create(uri);
            translationWebRequest.Headers.Add("Authorization", headerValue);
            System.Net.WebResponse response         = translationWebRequest.GetResponse();
            System.IO.Stream       stream           = response.GetResponseStream();
            System.Text.Encoding   encode           = System.Text.Encoding.GetEncoding("utf-8");
            System.IO.StreamReader translatedStream = new System.IO.StreamReader(stream, encode);
            string responseStr = translatedStream.ReadToEnd();

            System.Xml.XmlDocument xTranslation = new System.Xml.XmlDocument();
            xTranslation.LoadXml(responseStr);
            string translatedText = xTranslation.InnerText;
        }
Exemplo n.º 31
0
        public void Run(bool testRun)
        {
            if (!(IsValid && ((parent as Document.Target).IsValid))) throw new InvalidOperationException("Only valid tests on valid targets can be run.");

            Target target = parent as Target;
            if (target == null) throw new ApplicationException("Internal Error: unable to access target for this test.");

            if (relativePath == null) relativePath = "";

            string targetPath = target.Path.TrimEnd('/');
            string fullPath = targetPath + "/" + relativePath.TrimStart('/');

            string paramString = "";
            foreach (TestParameter p in parameters)
            {
                if (paramString != "") paramString += "&";

                paramString += System.Web.HttpUtility.UrlEncode(p.Name);
                if (!string.IsNullOrEmpty(p.Value))
                    paramString += "=" + System.Web.HttpUtility.UrlEncode(p.Value);
            }

            request = null;
            System.Net.HttpWebResponse response = null;

            int responseStatusCode = int.MinValue;
            string responseBody = null;

            try
            {
                if (!testRun)
                {
                    Status = TestStatusType.Executing;
                    StatusMessage = "Test is now executing.";
                }

                switch (method)
                {
                    case MethodType.GET:
                        if (paramString != "") fullPath += "?" + paramString;
                        request = System.Net.WebRequest.Create(fullPath);
                        request.Method = "GET";
                        break;
                    case MethodType.POST:
                        request = System.Net.WebRequest.Create(fullPath);
                        request.ContentType = "application/x-www-form-urlencoded";
                        request.Method = "POST";
                        byte[] paramBytes = System.Text.Encoding.ASCII.GetBytes(paramString);
                        request.ContentLength = paramBytes.Length;
                        request.GetRequestStream().Write(paramBytes, 0, paramBytes.Length);
                        break;
                }

                response = (System.Net.HttpWebResponse) request.GetResponse();
                responseStatusCode = (int)response.StatusCode;

                System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream());
                responseBody = sr.ReadToEnd();

                if (!testRun)
                {
                    Status = TestStatusType.Succeeded;
                    StatusMessage = "Test executed successfully.";
                }
            }
            catch (System.Net.WebException wex)
            {
                if (wex.Response != null)
                {
                    System.Net.HttpWebResponse wr = (System.Net.HttpWebResponse)wex.Response;
                    responseStatusCode = (int)wr.StatusCode;
                }

                if (!testRun)
                {
                    if (wex.Status == System.Net.WebExceptionStatus.RequestCanceled)
                    {
                        Status = TestStatusType.Cancelled;
                        StatusMessage = "User cancelled.";
                    }
                    else
                    {
                        Status = TestStatusType.Failed;
                        StatusMessage = wex.Message;
                    }
                }

                if (testRun)
                    throw;
            }
            catch (Exception ex)
            {
                if (!testRun)
                {
                    Status = TestStatusType.Failed;
                    StatusMessage = ex.Message;
                }

                if (testRun)
                    throw;
            }
            finally
            {
                this.responseStatusCode = responseStatusCode;
                this.responseBody = responseBody;

                foreach (Document.Alert alert in alerts)
                {
                    ICondition condition = alert.Condition as ICondition;
                    condition.SetResponseBody(responseBody);
                    condition.SetResponseStatusCode(responseStatusCode);
                }
            }
        }