UploadValues() public method

public UploadValues ( System address, System data ) : byte[]
address System
data System
return byte[]
Example #1
0
        private void button1_Click(object sender, EventArgs e)
        {
            System.Net.WebClient WebClientObj = new System.Net.WebClient();

            System.Collections.Specialized.NameValueCollection PostVars = new System.Collections.Specialized.NameValueCollection();

            PostVars.Add("userPass", textBox2.Text.Trim());

            PostVars.Add("userName", textBox1.Text.Trim());

            PostVars.Add("platform", "android");

            try

            {
                WebClientObj.Encoding = Encoding.UTF8;

                byte[] byRemoteInfo = WebClientObj.UploadValues("http://xxzy.xinkaoyun.com:8081/holidaywork/login", "POST", PostVars);

                //下面都没用啦,就上面一句话就可以了

                string sRemoteInfo = System.Text.Encoding.UTF8.GetString(byRemoteInfo);

                LoginObj = JsonConvert.DeserializeObject <Root_1>(sRemoteInfo);

                PostVars.Clear();

                PostVars.Add("token", LoginObj.data.andToken);

                byRemoteInfo = WebClientObj.UploadValues("http://xxzy.xinkaoyun.com:8081/holidaywork/student/getStudent", "POST", PostVars);

                sRemoteInfo = System.Text.Encoding.UTF8.GetString(byRemoteInfo);

                MessageBox.Show(LoginObj.msg);

                LoginObj_2 = JsonConvert.DeserializeObject <Root_2>(sRemoteInfo);

                if (LoginObj.msg == "登录成功")
                {
                    this.Hide();
                    main.Show();
                }
                //这是获取返回信息
            }

            catch
            {
            }
        }
Example #2
0
    public static string GetPost(string url, params string[] data)
    {
        string tempMessage = "";

        System.Net.WebClient WebClientObj = new System.Net.WebClient();
        System.Collections.Specialized.NameValueCollection PostVars = new System.Collections.Specialized.NameValueCollection();
        if (data.Length % 2 == 0)
        {
            for (int i = 0; i < (data.Length / 2); i++)
            {
                PostVars.Add(data[i * 2], data[i * 2 + 1]);
            }
        }

        try
        {
            byte[] byRemoteInfo = WebClientObj.UploadValues(url, "POST", PostVars);
            //下面都没用啦,就上面一句话就可以了
            tempMessage = System.Text.Encoding.Default.GetString(byRemoteInfo);
            //这是获取返回信息
        }
        catch (Exception ex)
        {
            //throw ex;
        }
        return(tempMessage);
    }
        public OAuthResponse RequestToken(string code)
        {
            NameValueCollection parameters = new NameValueCollection
                                                 {
                                                     { "client_id", this.config.ClientId },
                                                     { "client_secret", this.config.ClientSecret },
                                                     { "grant_type", "authorization_code" },
                                                     {
                                                         "redirect_uri",
                                                         this.config.RedirectUri
                                                     },
                                                     { "code", code }
                                                 };

            var client = new WebClient();
            var result = client.UploadValues("https://api.instagram.com/oauth/access_token", "POST", parameters);
            var response = System.Text.Encoding.Default.GetString(result);
            var responseObject = (JObject)JsonConvert.DeserializeObject(response);

            return new OAuthResponse()
                       {
                           AccessToken = (string)responseObject["access_token"],
                           User = new UserInfo()
                                    {
                                        Id = Convert.ToInt64(responseObject["user"]["id"]),
                                        Username = responseObject["user"]["username"].ToString(),
                                        FullName = responseObject["user"]["full_name"].ToString(),
                                        ProfilePicture = responseObject["user"]["profile_picture"].ToString()
                                    }
                       };
        }
        /// <summary>
        /// Explicitly refreshes the Google Auth Token.  Usually not necessary.
        /// </summary>
        public void RefreshGoogleAuthToken()
        {
            string authUrl = "https://www.google.com/accounts/ClientLogin";

            var data = new NameValueCollection();

            data.Add("Email", this.androidSettings.SenderID);
            data.Add("Passwd", this.androidSettings.Password);
            data.Add("accountType", "GOOGLE_OR_HOSTED");
            data.Add("service", "ac2dm");
            data.Add("source", this.androidSettings.ApplicationID);

            var wc = new WebClient();

            try
            {
                var authStr = Encoding.ASCII.GetString(wc.UploadValues(authUrl, data));

                //Only care about the Auth= part at the end
                if (authStr.Contains("Auth="))
                    googleAuthToken = authStr.Substring(authStr.IndexOf("Auth=") + 5);
                else
                    throw new GoogleLoginAuthorizationException("Missing Auth Token");
            }
            catch (WebException ex)
            {
                var result = "Unknown Error";
                try { result = (new System.IO.StreamReader(ex.Response.GetResponseStream())).ReadToEnd(); }
                catch { }

                throw new GoogleLoginAuthorizationException(result);
            }
        }
        /// <summary>
        ///     Starts the auth process and
        /// </summary>
        /// <returns>A new Token</returns>
        public Token DoAuth()
        {
            using (WebClient wc = new WebClient())
            {
                wc.Proxy = null;
                wc.Headers.Add("Authorization",
                    "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(ClientId + ":" + ClientSecret)));

                NameValueCollection col = new NameValueCollection
                {
                    {"grant_type", "client_credentials"},
                    {"scope", Scope.GetStringAttribute(" ")}
                };

                byte[] data;
                try
                {
                    data = wc.UploadValues("https://accounts.spotify.com/api/token", "POST", col);
                }
                catch (WebException e)
                {
                    using (StreamReader reader = new StreamReader(e.Response.GetResponseStream()))
                    {
                        data = Encoding.UTF8.GetBytes(reader.ReadToEnd());
                    }
                }
                return JsonConvert.DeserializeObject<Token>(Encoding.UTF8.GetString(data));
            }
        }
Example #6
0
        private string GetAccessToken()
        {
            try
            {
                byte[] credentials        = Encoding.UTF8.GetBytes(string.Format("{0}:{1}", _spotifySecrets.ClientId, _spotifySecrets.ClientSecret));
                string encodedCredentials = Convert.ToBase64String(credentials);
                Token  token = null;

                using (System.Net.WebClient web = new System.Net.WebClient())
                {
                    var data = new NameValueCollection();
                    data.Add(SPOTIFY_GRANT_TYPE_HEADER, SPOTIFY_GRANT_TYPE_VALUE);

                    web.Headers.Add(SPOTIFY_AUTHORIZATION_HEADER, string.Format("Basic {0}", encodedCredentials));
                    web.Encoding = Encoding.UTF8;

                    byte[] response = web.UploadValues(_spotifySecrets.TokenUrl, data);
                    token = JsonConvert.DeserializeObject <Token>(Encoding.UTF8.GetString(response));
                }

                return(token.AccessToken);
            }
            catch (Exception)
            {
                throw;
            }
        }
Example #7
0
        internal static void postItemType(modelPOS mPOS)
        {
            string result = "";
            try
            {
                if (mPOS.reason.Length > 2)
                {

                            using (WebClient client = new WebClient { UseDefaultCredentials = true })
                            {

                                byte[] response = client.UploadValues("http://api.olpl.org/api/positemcreate", new NameValueCollection()
                        {
                            { "transID", mPOS.transID.ToString() },
                            { "itemType", mPOS.reason },
                            { "itemQuantity", mPOS.quantity.ToString() },
                            { "itemPrice", mPOS.amtCol.ToString() },
                            { "itemID", mPOS.itemID },
                            { "totalPrice", mPOS.totalBill.ToString() },
                            { "itemTitle", mPOS.title },
                            { "itemAuthor", mPOS.author },
                            { "itemCallNumber", mPOS.callnumber },
                            { "transType", mPOS.transType },
                            { "stationType", mPOS.stationType }
                        });

                        result = System.Text.Encoding.UTF8.GetString(response);
                    }
                }
            }
            catch (Exception e1) {  }
            //return int.Parse(result);
        }
        /// <summary>
        /// Returns true if the captcha is successfully validated by google
        /// </summary>
        /// <param name="captchaCode"></param>
        /// <param name="userIpAddress"></param>
        /// <returns></returns>
        public static bool IsGoogleReCaptchaValid(string captchaCode, string userIpAddress)
        {
            try
            {
                WebClient client = new WebClient();
                NameValueCollection collection = new NameValueCollection()
            {
                {"secret", "6LdpLA0TAAAAALj2bvRJr4OEnpTq8ATFwLxm5_YU"},
                {"response", captchaCode},
                {"remoteip", userIpAddress}
            };

                byte[] resp = client.UploadValues("https://www.google.com/recaptcha/api/siteverify", collection);
                string output = System.Text.Encoding.UTF8.GetString(resp);

                //JObject o = JObject.Parse(output);
                JavaScriptSerializer jsonSerialiser = new JavaScriptSerializer();
                CaptchaResponse response = jsonSerialiser.Deserialize<CaptchaResponse>(output);

                return response.success == "True" ? true : false;
            }
            catch(Exception ex)
            {
                Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
                return false;
            }
        }
Example #9
0
        public string GetData(string url, NameValueCollection values,out Exception ex)
        {
            using (WebClient w = new WebClient())
            {

                w.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
                //System.Collections.Specialized.NameValueCollection  VarPar = new System.Collections.Specialized.NameValueCollection();
                //VarPar.Add("userAccount", "drcl1858");
                //VarPar.Add("pwd", "aHVpaGU4MDAz");
                //VarPar.Add("valid", "FB68F3B5FC7CF00F5701CD796F1C8649");
                string sRemoteInfo;
                byte[] byRemoteInfo;
                try
                {
                     byRemoteInfo = w.UploadValues(url, "POST", values);
                     sRemoteInfo = System.Text.Encoding.UTF8.GetString(byRemoteInfo);
                }
                catch(Exception e)
                {
                    ex = e;
                    return string.Empty ;
                }
                ex = null;
                return sRemoteInfo;
            }
        }
Example #10
0
 private static void UploadCrashLog()
 {
     string crashLog = FullPath;
       if (File.Exists(crashLog)) {
     Task.Factory.StartNew(() => {
       try {
     string crashText = File.ReadAllText(crashLog);
     //uncomment if we want to rename the crash log after uploading it
     //string oldPath = Path.ChangeExtension(crashLog, ".old");
     //if (File.Exists(oldPath))
     //  File.Delete(oldPath);
     //File.Move(crashLog, oldPath);
     using (var wb = new WebClient()) {
       var data = new NameValueCollection();
       data["id"] = disParity.Version.GetID().ToString();
       data["crash"] = crashText;
       Uri uri = new Uri(@"http://www.vilett.com/disParity/crash.php");
       byte[] response = wb.UploadValues(uri, "POST", data);
     }
       }
       catch (Exception e) {
     LogFile.Log("Error uploading crash log: " + e.Message);
       }
     });
       }
 }
Example #11
0
        //////////////////////////////////////////////////////////////////////////////
        // LogEvent.ashx is an entry point, to send data it's necessary to request it with appropriate parameters
        // (can use both GET and POST request methods)
        // parameters explanation
        // "MessageAppKey" identifies application that sends data
        // "MessageSession" unique identifier of user's session
        // "MessagesList" contains one or more message to send;
        // every it's line represents one message and consists of three columns delimited by tabs and ending with linefeed
        // these columns are:
        // time when event happened, UTC time zone, in this time format: "yyyy-MM-dd HH:mm:ss.fffffff"
        // name of the message type
        // message data
        // it's better to send multiple messages at once, because every web request can have big round-trip delay
        // samples of MessageName
        // "Event"
        // "Exception"
        // "Latency Login"
        // sample of the message line:
        // 2012-04-02 08:56:16.0527220\tLatency TestMethod\t0.0992977\r\n
        // response is empty on success, or contains error message otherwise
        //////////////////////////////////////////////////////////////////////////////
        static void Test()
        {
            // it's not recommended to use system clock for latency measurement, because it results can be very inaccurate
            // using profiling API class instead
            var watch = Stopwatch.StartNew();
            Thread.Sleep(100);
            watch.Stop();

            var latency = watch.Elapsed.TotalSeconds;

            var message1 = string.Format("{0}\t{1}\t{2}\r\n", DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fffffff"),
                "Event", "Test");
            var message2 = string.Format("{0}\t{1}\t{2}\r\n", DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fffffff"),
                "Latency TestMethod", latency.ToString(CultureInfo.InvariantCulture));

            var sessionId = Guid.NewGuid().ToString();
            var vals = new NameValueCollection
                {
                    { "MessageAppKey", "Sample_ReportingToAppMetrics" },
                    { "MessageSession", sessionId },
                    { "MessagesList", message1 + message2 },
                };

            // it's better to send data from the secondary thread, but in this sample using only one thread in the sake of simplicity
            using (var client = new WebClient())
            {
                var response = client.UploadValues(ServerUrl, "POST", vals);
                var responseText = Encoding.ASCII.GetString(response);
                if (!string.IsNullOrEmpty(responseText))
                    throw new ApplicationException(responseText);
            }
        }
        public Token GetToken()
        {
            // web client
            var client = new System.Net.WebClient();


            // invoke the REST method
            client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            string credentials = Convert.ToBase64String(
                Encoding.ASCII.GetBytes(string.Format("{0}:{1}", _credentials.ClientId, _credentials.ClientSecret)));


            client.Headers[HttpRequestHeader.Authorization] = string.Format("Basic {0}", credentials);
            var postVaules = new NameValueCollection
            {
                {"username",_credentials.Username},
                {"password", _credentials.Password},
                {"grant_type", GrantTpype.Password}
            };
            try
            {
                byte[] result = client.UploadValues(TokenUrl, "POST", postVaules);
                var jsonData = Encoding.UTF8.GetString(result);
                var token = JsonConvert.DeserializeObject<Token>(jsonData);
                return token;
            }
            catch (WebException ex)
            {
                if (((HttpWebResponse)ex.Response).StatusCode == HttpStatusCode.BadRequest)
                {
                    throw new WebException("Failed to request access token. Check you OAuth credentials.");
                }
            }
            return null;
        }
 private string PostRequest(string url, NameValueCollection data)
 {
     WebClient wc = new WebClient();
     byte[] b = wc.UploadValues(url, data);
     string s = System.Text.Encoding.UTF8.GetString(b);
     return s;
 }
 public void Send()
 {
     using (var wc = new WebClient())
     {
         wc.UploadValues(EndpointUri, GetNameValueCollection());
     }
 }
Example #15
0
        public static ImageInfo toImgur(Bitmap bmp)
        {
            ImageConverter convert = new ImageConverter();
            byte[] toSend = (byte[])convert.ConvertTo(bmp, typeof(byte[]));
            using (WebClient wc = new WebClient())
            {
                NameValueCollection nvc = new NameValueCollection
                {
                    { "image", Convert.ToBase64String(toSend) }
                };
                wc.Headers.Add("Authorization", Imgur.getAuth());
                ImageInfo info = new ImageInfo();
                try  
                {
                    byte[] response = wc.UploadValues("https://api.imgur.com/3/upload.xml", nvc);
                    string res = System.Text.Encoding.Default.GetString(response);

                    var xmlDoc = new System.Xml.XmlDocument();
                    xmlDoc.LoadXml(res);
                    info.link = new Uri(xmlDoc.SelectSingleNode("data/link").InnerText);
                    info.deletehash = xmlDoc.SelectSingleNode("data/deletehash").InnerText;
                    info.id = xmlDoc.SelectSingleNode("data/id").InnerText;
                    info.success = true;
                }
                catch (Exception e)
                {
                    info.success = false;
                    info.ex = e;
                }
                return info;
            }
        }
        //Function used to get instagram user id and access token
        public static InstagramRootObject GetDataInstagramToken(string code)
        {
            try
            {
                var parameters = new NameValueCollection
                {
                    {"client_id", ConfigurationManager.AppSettings["instagram.clientid"]},
                    {"client_secret", ConfigurationManager.AppSettings["instagram.clientsecret"]},
                    {"grant_type", "authorization_code"},
                    {"redirect_uri", ConfigurationManager.AppSettings["instagram.redirecturi"]},
                    {"code", code}
                };

                var client = new WebClient();
                var result = client.UploadValues("https://api.instagram.com/oauth/access_token", "POST", parameters);
                var response = System.Text.Encoding.Default.GetString(result);

                // deserializing nested JSON string to object
                var jsResult = JsonConvert.DeserializeObject<InstagramRootObject>(response);
                return jsResult;
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Example #17
0
        private string GetOutput(string res, string file_name)
        {
            try {

               	        WebClient client = new WebClient();
                NameValueCollection form = new NameValueCollection();

                form.Add("login", Properties.Settings.Default.login);
                form.Add("token", Properties.Settings.Default.api);
                form.Add(String.Format("file_ext[{0}]", file_name), Path.GetExtension(file_name));
                form.Add(String.Format("file_name[{0}]", file_name),file_name );
                form.Add(String.Format("file_contents[{0}]", file_name), res);
                byte[] responseData = client.UploadValues(API_URL, form);
                String s =  Encoding.UTF8.GetString(responseData);
                System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex("\"repo\":\"(\\d+)\"");
                System.Text.RegularExpressions.Match m = r.Match(s);

                if(m.Success){
                    return String.Format("<script src=\"http://gist.github.com/{0}.js\"></script>", m.Groups[1].Value);
                }
                return null;
            }
            catch (Exception webEx) {
              	    Console.WriteLine(webEx.ToString());

            }

            return null;
        }
Example #18
0
        public static string Post(string WebUrl, System.Collections.Specialized.NameValueCollection nv)
        {
            string content = "";
            if (nv == null)
                nv = new System.Collections.Specialized.NameValueCollection();
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(WebUrl);
                //HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.lebi.cn");
                request.Timeout = 1000 * 15;
                //HttpWebResponse myResponse = (HttpWebResponse)request.GetResponse();
                //if (myResponse.StatusDescription.ToString().ToUpper() == "OK")
                //{
                    StringWriter sw = new StringWriter();
                    string url = WebUrl;
                    System.Net.WebClient wc = new System.Net.WebClient();
                    byte[] b = wc.UploadValues(WebUrl, "POST", nv);
                    content = System.Text.Encoding.GetEncoding("utf-8").GetString(b);
                //}

            }
            catch (Exception ex)
            {
                return ex.Message;
            }

            return content;
        }
Example #19
0
    string ToPost()
    {
        System.Net.WebClient WebClientObj = new System.Net.WebClient();
        System.Collections.Specialized.NameValueCollection PostVars = new System.Collections.Specialized.NameValueCollection();
        string[] AllKey = HttpContext.Current.Request.Params.AllKeys;
        if (AllKey.Length > 0)
        {
            foreach (string key in AllKey)
            {
                PostVars.Add(key, Common.PageInput.ReStr(key, ""));
            }
        }
        else
        {
            return("");
        }

        PostVars.Add("para", "GetArticleInfo");
        PostVars.Add("ArticleId", "14031705174932481508");
        try
        {
            byte[] byRemoteInfo = WebClientObj.UploadValues("http://www.yyinfo.net/aar/", "POST", PostVars);
            //下面都没用啦,就上面一句话就可以了
            string sRemoteInfo = System.Text.Encoding.UTF8.GetString(byRemoteInfo);
            //这是获取返回信息
            return(sRemoteInfo);
        }
        catch (Exception ex)
        {
            return(ex.ToString());
        }
    }
        private static void SendInstallData(string error)
        {
            try
            {
                using (var client = new WebClient())
                {
                    var data = new NameValueCollection();
                    data.Add("error", error);
                    data.Add("computername", SystemInformation.ComputerName);

                    using (var mgmt = new ManagementClass("Win32_OperatingSystem"))
                    {
                        try
                        {
                            foreach (ManagementObject mgmtObj in mgmt.GetInstances())
                            {
                                // Just get first value.
                                data.Add("os", mgmtObj["Caption"].ToString().Trim());
                                break;
                            }
                        }
                        catch { }
                        var result = System.Text.Encoding.Default.GetString(client.UploadValues("http://www.filmkhoj.com/api/install", data));
                    }
                }
            }
            catch { }
        }
Example #21
0
        /// <summary>
        /// Used to generate token
        /// </summary>
        /// <returns></returns>
        private static string GenerateToken()
        {
            var client     = new System.Net.WebClient();
            var parameters = new NameValueCollection();

            if (_authenticationToken != null)
            {
                try
                {
                    client.Headers[HttpRequestHeader.Authorization] = "Bearer " + _authenticationToken.access_token;
                    var resultAuthByte = client.DownloadString(ApiUrlManager.BaseUrl + "/api/Token/RefeshTokenMain");
                    return(_authenticationToken.access_token);
                }
                catch (Exception)
                {
                }
            }

            parameters = new NameValueCollection();
            parameters.Add("grant_type", "password");
            parameters.Add("username", UserName);
            parameters.Add("password", Password);

            var resultByte = client.UploadValues(ApiUrlManager.BaseUrl + "/oauth/token", "POST", parameters);

            _authenticationToken =
                new JavaScriptSerializer().Deserialize <AuthenticationToken>(Encoding.Default.GetString(resultByte));
            return(_authenticationToken.access_token);
        }
Example #22
0
        public override int Run(string[] remainingArguments)
        {
            using(var client = new WebClient())
            {
                var postParameters = new NameValueCollection();
                postParameters.Add("client_id", client_id);
                postParameters.Add("client_secret", client_secret);
                postParameters.Add("grant_type", "client_credentials");
                var authResult = client.UploadValues("https://api.cheezburger.com/oauth/access_token", "POST",
                                                     postParameters);

                var authResultText = new StreamReader(new MemoryStream(authResult), Encoding.UTF8).ReadToEnd();

                var deserializedAuthResult = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(authResultText, new
                    {
                        access_token = "string",
                        expires_in = 123,
                        refresh_token = "string"
                    });

                var result = client.DownloadString("https://api.cheezburger.com/v1/ohai?access_token=" + deserializedAuthResult.access_token);
                Console.WriteLine(result);
            }

            return 0;
        }
Example #23
0
        //public static DateTime GetNowTime()
        //{

        //    string url = "http://time.tianqi.com/beijing/";
        //    HtmlWeb htmlWeb = new HtmlWeb();
        //    HtmlAgilityPack.HtmlDocument htmlDocument = htmlWeb.Load(url);
        //    string XPath = "//*[@id=\"clock\"]";

        //    HtmlNodeCollection hrefList = htmlDocument.DocumentNode.SelectNodes(XPath);
        //    if (hrefList != null)
        //    {
        //        foreach (HtmlNode href in hrefList)
        //        {
        //            //DateTime dateTime=DateTime.ParseExact(href.InnerText, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
        //            return dateTime;
        //        }

        //    }
        //    return DateTime.MaxValue;
        //}
        public static string Post(string URL, Dictionary <string, string> _PostVars)
        {
            System.Net.WebClient WebClientObj = new System.Net.WebClient();

            System.Collections.Specialized.NameValueCollection PostVars = new System.Collections.Specialized.NameValueCollection();

            foreach (var item in _PostVars)
            {
                PostVars.Add(item.Key, item.Value);
            }

            try
            {
                byte[] byRemoteInfo = WebClientObj.UploadValues(URL, "POST", PostVars);

                //下面都没用啦,就上面一句话就可以了

                string sRemoteInfo = System.Text.Encoding.UTF8.GetString(byRemoteInfo);

                return(sRemoteInfo);
                //这是获取返回信息
            }

            catch

            {
                throw;
            }
        }
 public static string[] Pull(string url, NameValueCollection postfields)
 {
     WebClient webclient = new WebClient();
     byte[] responsebytes = webclient.UploadValues("http://"+url, "POST", postfields);
     string responsefromserver = Encoding.UTF8.GetString(responsebytes);
     return SplitString(responsefromserver);
 }
Example #25
0
 public string ApiGetBadIports()
 {
     TraceLogObj.WriteToLog(ThreadName, ObjectName, GetCurrentMethod(), "Start Call: ApiGetBadIports");
     TraceLogObj.WriteToLog(_ThreadName, ObjectName, GetCurrentMethod(), ApiCompiledPath + "schedule.php  ---- Get Bad Imports.");
     string response;
     //Console.WriteLine("Upload FIle: " + UploadFile);
     using (WebClient client = new WebClient())
     {
         NameValueCollection parameters = InitParameters();
         TraceLogObj.WriteToLog(_ThreadName, ObjectName, GetCurrentMethod(), parameters.Get("username"));
         TraceLogObj.WriteToLog(_ThreadName, ObjectName, GetCurrentMethod(), parameters.Get("apikey"));
         parameters.Add("func", "bad");
         try
         {
             var responseBytes = client.UploadValues(ApiCompiledPath + "schedule.php", "POST", parameters);
             response = Encoding.ASCII.GetString(responseBytes);
         }
         catch (Exception e)
         {
             response = "Error";
             TraceLogObj.WriteToLog(_ThreadName, ObjectName, GetCurrentMethod(), e.Message);
         }
     }
     TraceLogObj.WriteToLog(ThreadName, ObjectName, GetCurrentMethod(), "End Call: ApiGetBadIports");
     return response;
 }
 private void SendResponse(HttpResponse httpResponse, string URL, string PostFormVariable, string samlResponse)
 {
     List<string> SPLogOutURLs = ConfigurationManager.AppSettings["SPLogOutURLs"].Split(',').Select(s => s.ToString()).ToList();
     if(SPLogOutURLs.Count>0)
     {
         Uri currentURI = new Uri(URL.ToLower());
         foreach (string s in SPLogOutURLs)
         {
             Uri sURL = new Uri(s.ToLower());
             var result = Uri.Compare(currentURI, sURL, UriComponents.Host | UriComponents.PathAndQuery, UriFormat.SafeUnescaped, StringComparison.OrdinalIgnoreCase);
             if (result != 0)
             {
                 using (var client = new WebClient())
                 {
                     var values = new NameValueCollection();
                     values[PostFormVariable] = HttpUtility.HtmlEncode(samlResponse);
                     var response = client.UploadValues(s, values);
                     //var responseString = Encoding.Default.GetString(response);
                 }
             }
         }
     }
     SAMLForm samlForm = new SAMLForm();
     samlForm.ActionURL = URL;
     samlForm.AddHiddenControl(PostFormVariable, samlResponse);
     samlForm.Write(httpResponse);
 }
Example #27
0
        private static string GetSwtTokenFromAcs(string serviceNamespace, string clientId, string clientSecret, string scope)
        {
            WebClient client = new WebClient();

            client.BaseAddress = string.Format(CultureInfo.CurrentCulture,
                                               "https://{0}.{1}",
                                               serviceNamespace,
                                               "accesscontrol.windows.net");

            NameValueCollection values = new NameValueCollection();
            values.Add("grant_type", "client_credentials");
            values.Add("client_id", clientId);
            values.Add("client_secret", clientSecret);
            values.Add("scope", scope);

            byte[] responseBytes = null;
            try
            {
                responseBytes = client.UploadValues("/v2/OAuth2-13", "POST", values);
            }
            catch (WebException ex)
            {
                throw new InvalidOperationException(new StreamReader(ex.Response.GetResponseStream()).ReadToEnd());
            }
            string response = Encoding.UTF8.GetString(responseBytes);

            // Parse the JSON response and return the access token
            var serializer = new JavaScriptSerializer();

            Dictionary<string, object> decodedDictionary = serializer.DeserializeObject(response) as Dictionary<string, object>;

            return decodedDictionary["access_token"] as string;
        }
Example #28
0
        string LogInToPasteBin()
        {
            if (_pastebinUserKey != null)
                return _pastebinUserKey;

            string userName = "******";
            string pwd = "";

            NameValueCollection values = new NameValueCollection();
            values.Add("api_dev_key", pastebin_dev_key);
            values.Add("api_user_name", userName);
            values.Add("api_user_password", pwd);

            using (WebClient wc = new WebClient())
            {
                byte[] respBytes = wc.UploadValues(pastebin_login_url, values);
                string resp = Encoding.UTF8.GetString(respBytes);
                if (resp.Contains("Bad API request"))
                {
                    Console.Write("Error:" + resp);
                    return null;
                }
                _pastebinUserKey = resp;
            }
            return _pastebinUserKey;
        }
        public static void IssueReport(AhhhDragonsReport report)
        {
            if (!(report.Map == 38 || report.Map == 94 || report.Map == 95 || report.Map == 96))
                return;

            var serializer = new JavaScriptSerializer();
            if (!string.IsNullOrWhiteSpace(report.Name))
            {
                using (var wb = new WebClient())
                {

                    var data = new NameValueCollection();

                    data["mtc"] = report.MistsTrackingCode;
                    data["name"] = report.Name;
                    data["map"] = report.Map.ToString();
                    data["posx"] = report.PosX.ToString();
                    data["posy"] = report.PosY.ToString();
                    data["posz"] = report.PosZ.ToString();
                    data["friendly"] = report.GroupAllegiance == AhhhDragonsReport.PlayerGroupAllegiance.Friend ? "1" : "0";
                    data["size"] = ((int)report.GroupSize).ToString();

                    var response = wb.UploadValues("http://ahhhdragons.com/db/wvw.php", "POST", data);
                    System.Diagnostics.Debug.WriteLine(Encoding.ASCII.GetString(response));

                }

            }
        }
 public string SendMessage(ISMSMessage m)
 {
     var message = (SMSMessage)m;
     var builder = new StringBuilder();
     string[] strArray = WebConfigurationManager.AppSettings.GetValues("SILVERSTREET_SMSServiceURL");
     if (strArray != null)
     {
         builder.Append(strArray[0]);
     }
     var data = new NameValueCollection();
     string[] values = WebConfigurationManager.AppSettings.GetValues("SILVERSTREET_SMSServiceUsername");
     if (values != null)
     {
         data.Add("username", values[0]);
     }
     string[] strArray3 = WebConfigurationManager.AppSettings.GetValues("SILVERSTREET_SMSServicePassword");
     if (strArray3 != null)
     {
         data.Add("password", strArray3[0]);
     }
     data.Add("destination", _formatter.FormatPhoneNumber(message.Recipient));
     string[] strArray4 = WebConfigurationManager.AppSettings.GetValues("SILVERSTREET_SMSDefaultSender");
     if (strArray4 != null)
     {
         data.Add("sender", strArray4[0]);
     }
     data.Add("body", message.Body);
     using (var client = new WebClient())
     {
         byte[] bytes = client.UploadValues(new Uri(builder.ToString()), "POST", data);
         return new UTF8Encoding().GetString(bytes);
     }
 }
Example #31
0
        /// <summary>
        /// Posts a request and deseralizes the response
        /// </summary>
        public static T JsonDeseralizePostResponse <T>(string Url, NameValueCollection Data)
        {
            var client = new System.Net.WebClient();

            byte[] response = client.UploadValues(Url, Data);
            return(Utility.JsonDeseralizeUtf8 <T>(response));
        }
        public string CompleteAuth(string verifier)
        {
            JObject o;
            using (var client = new WebClient())
            {
                var responseBytes =
                    client.UploadValues(accessTokenUrl, new NameValueCollection()
                    {
                        {"grant_type", "authorization_code" },
                        {"code", verifier },
                        {"client_id", ClientId },
                        {"client_secret", ClientSecret },
                        {"redirect_uri", @"https://loqu8.com" },
                    });

                // e.g., { "access_token":"xb7b51c9743595cf3111b10d275c8f3c6be20fcfad73c40aea83a12bf661b4d6","token_type":"bearer","expires_in":7200,"refresh_token":"xc1102ea910804c11b0e17a4a925e08ec655a095a6756de67aa886c6f621e890","scope":"wallet:accounts:read"}
                var json = Encoding.UTF8.GetString(responseBytes);
                o = JObject.Parse(json);
            }

            _accessToken = (string)o.SelectToken("access_token");
            _refreshToken = (string)o.SelectToken("refresh_token");

            return _accessToken;
        }
        static void Main(string[] args)
        {
            string accessToken;

            //first request a token from the Authorization Server
            using (var asClient = new WebClient())
            {
                var postValues = new NameValueCollection {{"grant_type", "password"}};

                asClient.Headers.Add("Authorization", "Basic YmM4NTJmZGIzMTFkNGFkYjlkMjJkZmE4MjI2YjM5MWE6TXpBMU1ESTRNVGhsWmpVeE5EVm1OVGd6TkRNMllXSTRNelE0TnpnM05qZz0=");
                asClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

                byte[] result = asClient.UploadValues("http://authz.test.com/oauth2/token","POST", postValues);
                string receivedResponseData = Encoding.UTF8.GetString(result);
                dynamic parsedData = JsonConvert.DeserializeObject<dynamic>(receivedResponseData);

                accessToken = parsedData.access_token.ToString();
            }

            //now request a list of roles from the resource server
            using (var rsClient = new WebClient())
            {
                rsClient.Headers.Add("Authorization", string.Concat("Bearer", " ", accessToken));
                rsClient.Headers.Add("Content-Type", "application/json");
                byte[] result = rsClient.DownloadData("http://resz.test.com/resz/GetAllRoles");
                string receivedResponseData = Encoding.UTF8.GetString(result);
                string[] parsedData = JsonConvert.DeserializeObject<string[]>(receivedResponseData);
            }
        }
Example #34
0
        /// <summary>
        /// Send a message to the QuantConnect Chart Streaming API.
        /// </summary>
        /// <param name="userId">User Id</param>
        /// <param name="apiToken">API token for authentication</param>
        /// <param name="packet">Packet to transmit</param>
        public static void Transmit(int userId, string apiToken, Packet packet)
        {
            try
            {
                using (var client = new WebClient())
                {
                    var tx = JsonConvert.SerializeObject(packet);
                    if (tx.Length > 10000)
                    {
                        Log.Trace("StreamingApi.Transmit(): Packet too long: " + packet.GetType());
                    }

                    var response = client.UploadValues("http://streaming.quantconnect.com", new NameValueCollection
                    {
                        {"uid", userId.ToString()},
                        {"token", apiToken},
                        {"tx", tx}
                    });

                    Log.Trace("StreamingApi.Transmit():  Sending Packet ({0})", packet.GetType());

                    //Deserialize the response from the streaming API and throw in error case.
                    var result = JsonConvert.DeserializeObject<Response>(System.Text.Encoding.UTF8.GetString(response));
                    if (result.Type == "error")
                    {
                        throw new Exception(result.Message);
                    }
                }
            }
            catch (Exception err)
            {
                Log.Error(err);
            }
        }
Example #35
0
        public static string SendCommand(string cmd, string param, MessageType type)
        {
            string response = "";

            using (var wb = new WebClient())
            {
                NetworkCredential cred = new NetworkCredential(Config.WebIOPiUser, Config.WebIOPiPassword);
                wb.Credentials = cred;

                Console.WriteLine("Sending command to  Pi " + Config.WebIOPiURI + cmd);

                if (type == MessageType.GET)
                {
                    response = wb.DownloadString(Config.WebIOPiURI + cmd);
                }
                else if(type == MessageType.POST)
                {
                    var data = new NameValueCollection();

                    data["username"] = "******";
                    data["password"] = "******";

                    var result = wb.UploadValues(Config.WebIOPiURI + cmd, data);
                    response = Encoding.Default.GetString(result);
                }
            }

            Console.WriteLine("Received response from Pi : " + response);

            return response;
        }
Example #36
0
 public static string PostRequest(string url, NameValueCollection param)
 {
     using (var wb = new WebClient())
     {
         return Encoding.UTF8.GetString(wb.UploadValues(url, "POST", param));
     }
 }
Example #37
0
        private static string GetTokenFromACS(string scope)
        {
            string wrapPassword = pwd;
            string wrapUsername = uid;

            // request a token from ACS 
            WebClient client = new WebClient();
            client.BaseAddress = string.Format("https://{0}.{1}", serviceNamespace, acsHostUrl);

            NameValueCollection values = new NameValueCollection();
            values.Add("wrap_name", wrapUsername);
            values.Add("wrap_password", wrapPassword);
            values.Add("wrap_scope", scope);

            byte[] responseBytes = client.UploadValues("WRAPv0.9/", "POST", values);

            string response = Encoding.UTF8.GetString(responseBytes);

            Console.WriteLine("\nreceived token from ACS: {0}\n", response);

            return HttpUtility.UrlDecode(
                response
                .Split('&')
                .Single(value => value.StartsWith("wrap_access_token=", StringComparison.OrdinalIgnoreCase))
                .Split('=')[1]);
        }
Example #38
0
    public static string CallRestService(string url, Connector.QueryParameter queryParameter)
    {
        System.Net.WebClient client = new System.Net.WebClient();
        client.BaseAddress = url;
        client.Encoding    = new UTF8Encoding();
        //client.Headers = new System.Net.WebHeaderCollection();
        //client.Headers.Add("Content-Type", "application/json");
        System.Collections.Specialized.NameValueCollection values = new System.Collections.Specialized.NameValueCollection();
        JavaScriptSerializer serializer = new JavaScriptSerializer();

        foreach (var param in queryParameter.Parameter)
        {
            string dictType   = typeof(Dictionary <string, object>).Name;
            string arrayType  = typeof(System.Collections.ArrayList).Name;
            string listType   = typeof(List <object>).Name;
            string paramValue = string.Empty;
            string paramType  = param.Value.GetType().Name;
            if (paramType == dictType || paramType == arrayType || paramType == listType)
            {
                paramValue = serializer.Serialize(param.Value);
            }
            else if (paramType == typeof(bool).Name)
            {
                paramValue = param.Value.Equals(true) ? "true" : "false";
            }
            else
            {
                paramValue = param.Value.ToString();
            }
            values.Add(param.Key, paramValue);
        }
        return(Encoding.UTF8.GetString(client.UploadValues(url, "POST", values)));

        // Add an Accept header for JSON format.
    }
Example #39
0
        public void RSPEC_WebClient(string address, Uri uriAddress, byte[] data,
                                    NameValueCollection values)
        {
            System.Net.WebClient webclient = new System.Net.WebClient();

            // All of the following are Questionable although there may be false positives if the URI scheme is "ftp" or "file"
            //webclient.Download * (...); // Any method starting with "Download"
            webclient.DownloadData(address);                            // Noncompliant
            webclient.DownloadDataAsync(uriAddress, new object());      // Noncompliant
            webclient.DownloadDataTaskAsync(uriAddress);                // Noncompliant
            webclient.DownloadFile(address, "filename");                // Noncompliant
            webclient.DownloadFileAsync(uriAddress, "filename");        // Noncompliant
            webclient.DownloadFileTaskAsync(address, "filename");       // Noncompliant
            webclient.DownloadString(uriAddress);                       // Noncompliant
            webclient.DownloadStringAsync(uriAddress, new object());    // Noncompliant
            webclient.DownloadStringTaskAsync(address);                 // Noncompliant

            // Should not raise for events
            webclient.DownloadDataCompleted   += Webclient_DownloadDataCompleted;
            webclient.DownloadFileCompleted   += Webclient_DownloadFileCompleted;
            webclient.DownloadProgressChanged -= Webclient_DownloadProgressChanged;
            webclient.DownloadStringCompleted -= Webclient_DownloadStringCompleted;


            //webclient.Open * (...); // Any method starting with "Open"
            webclient.OpenRead(address);
//          ^^^^^^^^^^^^^^^^^^^^^^^^^^^   {{Make sure that this http request is sent safely.}}
            webclient.OpenReadAsync(uriAddress, new object());              // Noncompliant
            webclient.OpenReadTaskAsync(address);                           // Noncompliant
            webclient.OpenWrite(address);                                   // Noncompliant
            webclient.OpenWriteAsync(uriAddress, "STOR", new object());     // Noncompliant
            webclient.OpenWriteTaskAsync(address, "POST");                  // Noncompliant

            webclient.OpenReadCompleted  += Webclient_OpenReadCompleted;
            webclient.OpenWriteCompleted += Webclient_OpenWriteCompleted;

            //webclient.Upload * (...); // Any method starting with "Upload"
            webclient.UploadData(address, data);                           // Noncompliant
            webclient.UploadDataAsync(uriAddress, "STOR", data);           // Noncompliant
            webclient.UploadDataTaskAsync(address, "POST", data);          // Noncompliant
            webclient.UploadFile(address, "filename");                     // Noncompliant
            webclient.UploadFileAsync(uriAddress, "filename");             // Noncompliant
            webclient.UploadFileTaskAsync(uriAddress, "POST", "filename"); // Noncompliant
            webclient.UploadString(uriAddress, "data");                    // Noncompliant
            webclient.UploadStringAsync(uriAddress, "data");               // Noncompliant
            webclient.UploadStringTaskAsync(uriAddress, "data");           // Noncompliant
            webclient.UploadValues(address, values);                       // Noncompliant
            webclient.UploadValuesAsync(uriAddress, values);               // Noncompliant
            webclient.UploadValuesTaskAsync(address, "POST", values);
//          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

            // Should not raise for events
            webclient.UploadDataCompleted   += Webclient_UploadDataCompleted;
            webclient.UploadFileCompleted   += Webclient_UploadFileCompleted;
            webclient.UploadProgressChanged -= Webclient_UploadProgressChanged;
            webclient.UploadStringCompleted -= Webclient_UploadStringCompleted;
            webclient.UploadValuesCompleted -= Webclient_UploadValuesCompleted;
        }
Example #40
0
        private static string getQueryResponse(NameValueCollection qData, string v)
        {
            string responseData;
            var    webClient = new System.Net.WebClient();
            var    response  = webClient.UploadValues(v, qData);

            responseData = System.Text.Encoding.UTF8.GetString(response);
            return(responseData);
        }
Example #41
0
        private static string getOverwriteResponse(NameValueCollection overwriteData, string publishURL)
        {
            string responseData;
            var    webClient = new System.Net.WebClient();
            var    response  = webClient.UploadValues(publishURL, overwriteData);

            responseData = System.Text.Encoding.UTF8.GetString(response);

            Thread.Sleep(60000);
            return(responseData);
        }
Example #42
0
 public string SendHttpPost()
 {
     //基础连接已经关闭: 未能为SSL/TLS 安全通道建立信任关系。
     ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate;
     System.Net.WebClient wc = new System.Net.WebClient();
     wc.Headers.Add("Accept-Language", "zh-cn");
     wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
     byte[] bytReturn = wc.UploadValues(Url, "post", Inputs);
     wc.Dispose();
     return(System.Text.Encoding.GetEncoding("utf-8").GetString(bytReturn));
 }
Example #43
0
    IEnumerator PostScores(int ID, int shots)
    {
        using (var wb = new System.Net.WebClient())
        {
            var data = new NameValueCollection();
            data["ID"]    = ID.ToString();
            data["shots"] = shots.ToString();

            var response = wb.UploadValues(addScoreURL, "POST", data);
            yield return(response);
        }
    }
        public ActionResult smsotp()
        {
            int otpValue = new Random().Next(100000, 999999);
            var status   = "";



            try
            {
                paresetEntities db        = new paresetEntities();
                var             mobileno  = db.Userinfoes.FirstOrDefault(u => u.username == User.Identity.Name);
                string          recipient = mobileno.phone.ToString();
                string          masked    = "(XXX) XXX-" + recipient.Substring(recipient.Length - 4);
                string          APIKey    = System.Configuration.ConfigurationManager.AppSettings["APIKey"].ToString();

                string message        = "Your OTP Number is " + otpValue + " ( Sent By : nexzip )";
                String encodedMessage = System.Web.HttpUtility.UrlEncode(message);

                using (var webClient = new System.Net.WebClient())
                {
                    byte[] response = webClient.UploadValues("https://api.textlocal.in/send/", new System.Collections.Specialized.NameValueCollection()
                    {
                        { "apikey", APIKey },
                        { "numbers", recipient },
                        { "message", encodedMessage },
                        { "sender", "TXTLCL" }
                    });

                    string result = System.Text.Encoding.UTF8.GetString(response);

                    var jsonObject = Newtonsoft.Json.Linq.JObject.Parse(result);

                    status = jsonObject["status"].ToString();

                    Session["CurrentOTP"] = otpValue;
                }


                //return Json(status, JsonRequestBehavior.AllowGet);
                OTPValidater obj = new OTPValidater();
                obj.msakmobilelable = "successfully send otp to you reg mobile number" + masked + status;
                obj.username        = User.Identity.Name.ToString();
                return(View(obj));
            }
            catch (Exception e)
            {
                OTPValidater obj = new OTPValidater();
                obj.msakmobilelable = "Error";
                obj.username        = User.Identity.Name.ToString();
                return(View(obj));
            }
        }
Example #45
0
 public static void AddRepoToTeam(string teamID, string orgName, string repoName)
 {
     try
     {
         string api       = "https://github.com/api/v2/json/teams/" + teamID + "/repositories?login=hnlam1986&token=1d095a1acc34a9bce4833f46551579e4";
         var    webClient = new System.Net.WebClient();
         NameValueCollection FormValues = new NameValueCollection();
         FormValues.Add("name", orgName + "/" + repoName);
         byte[] res = webClient.UploadValues(api, "POST", FormValues);
     }
     catch
     {
     }
 }
Example #46
0
        static void Example9()
        {
            string address = @"C:\Users\Giang\Desktop\UploadInHear.txt";

            System.Net.WebClient wc = new System.Net.WebClient();
            NameValueCollection  nameValueCollection = new NameValueCollection()
            {
                { "Name", "Giang" },
                { "Age", "23" }
            };

            byte[] response = wc.UploadValues(address, nameValueCollection);
            Console.WriteLine(response.Length);
        }
Example #47
0
    public static string postrequest(string url, System.Collections.Specialized.NameValueCollection PostVars)
    {
        try
        {
            System.Net.WebClient WebClientObj = new System.Net.WebClient();
            byte[] byRemoteInfo = WebClientObj.UploadValues(url, "POST", PostVars);

            string sRemoteInfo = System.Text.Encoding.UTF8.GetString(byRemoteInfo);
            return(sRemoteInfo);
        }
        catch (Exception ex)
        {
            return(ex.Message);
        }
    }
Example #48
0
    IEnumerator UpdateMaster()
    {
        while (true)
        {
            yield return(new WaitForSeconds(3540f));

            try
            {
                InitServData();
                wc = new System.Net.WebClient();
                wc.UploadValues(masterurl + "/updsvr.php", post_valid);
                wc.Dispose();
            }
            catch {}
        }
    }
    public object msg(string Number, string Message, string API_CODE)
    {
        object functionReturnValue = null;

        using (System.Net.WebClient client = new System.Net.WebClient())
        {
            System.Collections.Specialized.NameValueCollection parameter = new System.Collections.Specialized.NameValueCollection();
            string url = "https://www.itexmo.com/php_api/api.php";
            parameter.Add("1", Number);
            parameter.Add("2", Message);
            parameter.Add("3", API_CODE);
            dynamic rpb = client.UploadValues(url, "POST", parameter);
            functionReturnValue = (new System.Text.UTF8Encoding()).GetString(rpb);
        }
        return(functionReturnValue);
    }
Example #50
0
        public static XElement GetDocument(IMediaFile media)
        {
            ServicePoint servicePoint = ServicePointManager.FindServicePoint(new Uri("http://api.issuu.com/1_0"));

            servicePoint.Expect100Continue = false;
            System.Net.ServicePointManager.Expect100Continue = false;
            var data = IssuuApi.NewQuery("issuu.documents.list");

            data.Add("orgDocName", media.GetOrgName());
            IssuuApi.Sign(data);

            var client = new System.Net.WebClient();

            byte[] responseArray = client.UploadValues("http://api.issuu.com/1_0", data);
            return(GetDocument(Encoding.ASCII.GetString(responseArray)));
        }
        //########################################################################################
        //iTexmo API for C# / ASP --> go to www.itexmo.com/developers.php for API Documentation
        //########################################################################################
        public object itexmo(string Number, string Message, string API_CODE)
        {
            object functionReturnValue = null;

            using (System.Net.WebClient client = new System.Net.WebClient())
            {
                System.Collections.Specialized.NameValueCollection parameter = new System.Collections.Specialized.NameValueCollection();
                string url = "https://www.itexmo.com/php_api/api.php";
                parameter.Add("09565574596", Number);
                parameter.Add("This is your Verification Code ", Message);
                parameter.Add("TR-LOUHA804953_1J73K ", API_CODE);
                dynamic rpb = client.UploadValues(url, "POST", parameter);
                functionReturnValue = (new System.Text.UTF8Encoding()).GetString(rpb);
            }
            return(functionReturnValue);
        }
Example #52
0
        public static string WebClientData(string url, string method, NameValueCollection data, string proxyIP)
        {
            string    returnStr    = string.Empty;
            WebClient WebClientObj = new System.Net.WebClient();

            //HttpHelper.SetProxy(WebClientObj, proxyIP);
            try
            {
                byte[] byRemoteInfo = WebClientObj.UploadValues(url, method, data);
                returnStr = System.Text.Encoding.UTF8.GetString(byRemoteInfo);
            }
            catch (Exception ex)
            {
                returnStr = ex.ToString();
            }
            return(returnStr);
        }
Example #53
0
        public void SubscribeExpress100(string expressCompanyName, string number, string kuaidi100Key, string city, string redirectUrl)
        {                                                                        //使用快递100查询快递数据
            string kuaidi100Code = GetExpress(expressCompanyName).Kuaidi100Code; //根据快递公司名称获取对应的快递100编码

            if (string.IsNullOrEmpty(kuaidi100Key) || string.IsNullOrEmpty(expressCompanyName) || string.IsNullOrEmpty(number))
            {
                Core.Log.Info("没有设置快递100Key");
                return;
            }
            string url = "http://www.kuaidi100.com/poll";

            System.Net.WebClient WebClientObj = new System.Net.WebClient();
            NameValueCollection  PostVars     = new NameValueCollection();

            PostVars.Add("schema", "json");
            var model = new
            {
                company    = kuaidi100Code,
                number     = number,
                key        = kuaidi100Key,
                to         = city,
                parameters = new { callbackurl = redirectUrl }
            };
            var param = Newtonsoft.Json.JsonConvert.SerializeObject(model);

            PostVars.Add("param", param);
            try
            {
                byte[] byRemoteInfo = WebClientObj.UploadValues(url, "POST", PostVars);
                string output       = System.Text.Encoding.UTF8.GetString(byRemoteInfo);
                //注意返回的信息,只有result=true的才是成功
                var result = new { result = false, resultcode = "", message = "" };
                var m      = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(output, result);
                Core.Log.Info(output + "," + redirectUrl + "物流公司代码:" + kuaidi100Code + ",物流单号:" + number + ",物流到达城市:" + city); //日志记录看成功否
                if (!m.result)
                {
                    Core.Log.Error("物流通知订阅失败:" + result.message + ",物流公司代码:" + kuaidi100Code + ",物流单号:" + number + ",物流到达城市:" + city + ",快递Key:" + kuaidi100Key + "回调地址:" + redirectUrl);
                }
            }
            catch (Exception ex)
            {
                Core.Log.Error("物流通知订阅失败:" + ex.Message);
            }
        }
Example #54
0
        public object SendMessage(string number, string message, string code = "TR-SHOEM409737_6LTPQ")
        {
            object result = null;

            using (System.Net.WebClient client = new System.Net.WebClient())
            {
                NameValueCollection parameter = new NameValueCollection();
                string url = "https://www.itexmo.com/php_api/api.php";
                parameter.Add("1", number);
                parameter.Add("2", message);
                parameter.Add("3", code);

                dynamic rpb = client.UploadValues(url, "POST", parameter);

                result = (new System.Text.UTF8Encoding()).GetString(rpb);
            }

            return(result);
        }
        /// <summary>
        /// POST请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        public static string SendRequestData(string url, Dictionary <string, string> list)
        {
            System.Net.WebClient wc = new System.Net.WebClient();
            System.Collections.Specialized.NameValueCollection postVars = new System.Collections.Specialized.NameValueCollection();

            foreach (var item in list)
            {
                postVars.Add(item.Key, item.Value);
            }
            try
            {
                byte[] bytes = wc.UploadValues(url, "POST", postVars);

                return(Encoding.UTF8.GetString(bytes));
            }
            catch
            {
                return(null);
            }
        }
Example #56
0
        /// <summary>
        /// Hàm này dùng để gửi tin nhắn
        /// </summary>
        /// dien_thoai:0167834137-0987934822;noi_dung:Noi dung tin nhan;brand:TOPICA</param>
        /// <returns>Trả về 1: thành công; 0: lỗi</returns>
        public static string gui_tin_nhan(string ip_str_list_so_dien_thoai
                                          , string ip_str_noi_dung_gui
                                          , string ip_str_brand)
        {
            string v_str_output    = "0";
            string v_str_post_data = "dien_thoai:" + ip_str_list_so_dien_thoai + ";";

            v_str_post_data += "noi_dung:" + ip_str_noi_dung_gui + ";";
            v_str_post_data += "brand:" + ip_str_brand;

            using (System.Net.WebClient client = new System.Net.WebClient())
            {
                System.Collections.Specialized.NameValueCollection reqparm = new System.Collections.Specialized.NameValueCollection();
                reqparm.Add("data", v_str_post_data);
                reqparm.Add("token", "ngfj3215256jhkj3242jh465j4g548724g234g");
                byte[] responsebytes = client.UploadValues("http://sms.topica.edu.vn/api/send_sms_dvmc", "POST", reqparm);
                v_str_output = Encoding.UTF8.GetString(responsebytes);
            }
            return(v_str_output);
        }
Example #57
0
        public void execute()
        {
            string url = "http://localhost:58306/";

            try
            {
                System.Net.WebClient wc = new System.Net.WebClient();
                System.Collections.Specialized.NameValueCollection data =
                    new System.Collections.Specialized.NameValueCollection();
                data.Add("start_time", start.ToString());
                data.Add("end_time", end.ToString());
                data.Add("step_cnt", step.ToString());
                wc.UploadValues(url, data);
                wc.Dispose();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Example #58
0
        /// <summary>
        /// 向直接URL地址POST值并获取结果:PostVars 为JSON的参数个数
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public string Bost_PostUrl(string url, string postVarsValue)
        {
            string sRemoteInfo = string.Empty;

            System.Net.WebClient WebClientObj = new System.Net.WebClient();
            System.Collections.Specialized.NameValueCollection PostVars = new System.Collections.Specialized.NameValueCollection();
            if (postVarsValue != string.Empty)
            {
                PostVars.Add("postVars", postVarsValue);
            }
            try
            {
                byte[] byRemoteInfo = WebClientObj.UploadValues(url, "POST", PostVars);
                sRemoteInfo = System.Text.Encoding.UTF8.GetString(byRemoteInfo);
            }
            catch
            {
                sRemoteInfo = "error";
            }
            return(sRemoteInfo);
        }
Example #59
0
        public static string GetSMSEmail(string phone)
        {
            string smsEmail = "";

            using (WebClient webClient = new System.Net.WebClient())
            {
                NameValueCollection values = new NameValueCollection();
                values.Add("phonenum", phone);

                webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                byte[]          result           = webClient.UploadValues("http://www.freesmsgateway.info", "POST", values);
                string          ResultAuthTicket = Encoding.UTF8.GetString(result);
                string          source           = WebUtility.HtmlDecode(ResultAuthTicket);
                MatchCollection data             = Regex.Matches(source, @"SMS Gateway Address: \s*(.+?)\s*<br>", RegexOptions.Singleline);
                foreach (Match m in data)
                {
                    smsEmail = m.Groups[1].Value;
                }
            }
            return(smsEmail);
        }
Example #60
-1
        public string SendViaPasteBin(string body, string subject)
        {
            if(string.IsNullOrEmpty(subject)) {
                    subject = "Note " + DateTime.Now.ToLongDateString() + ":" + DateTime.Now.ToShortTimeString();
                }

                string api_paste_format = "csharp";
                string userk = LogInToPasteBin();

                NameValueCollection values = new NameValueCollection();
                values.Add("api_dev_key",pastebin_dev_key);
                values.Add("api_option","paste");
                values.Add("api_paste_code",body);
                values.Add("api_paste_private","1");
                values.Add("api_paste_name",subject);
                values.Add("api_paste_expire_date","10M");
                values.Add("api_paste_format",api_paste_format);
                values.Add("api_user_key",userk);

                using(WebClient wc = new WebClient()) {

                    byte[] respBytes = wc.UploadValues(pastebin_post_url,values);
                    string respString = Encoding.UTF8.GetString(respBytes);

                    Uri valid = null;
                    if(Uri.TryCreate(respString,UriKind.Absolute,out valid)) {
                       return valid.ToString();
                    }
                    else {
                        return respString;
                    }
                }
        }