UploadString() public method

public UploadString ( System address, string data ) : string
address System
data string
return string
コード例 #1
1
        public GamePlayHistory AddNewGameHistory(GamePlayHistory gamePlayHistory)
        {
            if (string.IsNullOrEmpty(ToSavourToken))
            {
                throw new InvalidOperationException("No ToSavour Token is set");
            }

            RequestClient = new WebClient();
            RequestClient.Headers.Add("Authorization", ToSavourToken);
            RequestClient.Headers.Add("Content-Type", "application/json");

            var memoryStream = new MemoryStream();
            GetSerializer(typeof(GamePlayHistory)).WriteObject(memoryStream, gamePlayHistory);

            memoryStream.Position = 0;
            var sr = new StreamReader(memoryStream);
            var json = sr.ReadToEnd();

            var userJsonString = RequestClient.UploadString(_host + @"gamehistories", json);

            var byteArray = Encoding.ASCII.GetBytes(userJsonString);
            var stream = new MemoryStream(byteArray);

            var returnedGamePlayHistory = GetSerializer(typeof(GamePlayHistory)).ReadObject(stream) as GamePlayHistory;

            return returnedGamePlayHistory;
        }
コード例 #2
0
ファイル: Program.cs プロジェクト: tian1ll1/WPF_Examples
        static void Main(string[] args)
        {
            Uri baseAddress = new Uri("http://localhost:8000");
            Console.WriteLine("Service is hosted at: " + baseAddress.AbsoluteUri);
            Console.WriteLine("Service help page is at: " + baseAddress.AbsoluteUri + "help");

            using (WebServiceHost host = new WebServiceHost(typeof(Service), baseAddress))
            {
                //WebServiceHost will automatically create a default endpoint at the base address using the
                //WebHttpBinding and the WebHttpBehavior, so there's no need to set that up explicitly
                host.Open();

                using (WebClient client = new WebClient())
                {
                    client.BaseAddress = baseAddress.AbsoluteUri;
                    client.QueryString["s"] = "hello";

                    Console.WriteLine("");

                    // Specify response format for GET using Accept header
                    Console.WriteLine("Calling EchoWithGet via HTTP GET and Accept header application/xml: ");
                    client.Headers[HttpRequestHeader.Accept] = "application/xml";
                    Console.WriteLine(client.DownloadString("EchoWithGet"));
                    Console.WriteLine("Calling EchoWithGet via HTTP GET and Accept header application/json: ");
                    client.Headers[HttpRequestHeader.Accept] = "application/json";
                    Console.WriteLine(client.DownloadString("EchoWithGet"));

                    Console.WriteLine("");

                    // Specify response format for GET using 'format' query string parameter
                    Console.WriteLine("Calling EchoWithGet via HTTP GET and format query string parameter set to xml: ");
                    client.QueryString["format"] = "xml";
                    Console.WriteLine(client.DownloadString("EchoWithGet"));
                    Console.WriteLine("Calling EchoWithGet via HTTP GET and format query string parameter set to json: ");
                    client.QueryString["format"] = "json";
                    Console.WriteLine(client.DownloadString("EchoWithGet"));

                    client.Headers[HttpRequestHeader.Accept] = null;

                    // Do POST in XML and JSON and get the response in the same format as the request
                    Console.WriteLine("Calling EchoWithPost via HTTP POST and request in XML format: ");
                    client.Headers[HttpRequestHeader.ContentType] = "application/xml";
                    Console.WriteLine(client.UploadString("EchoWithPost", "<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">bye</string>"));
                    Console.WriteLine("Calling EchoWithPost via HTTP POST and request in JSON format: ");
                    client.Headers[HttpRequestHeader.ContentType] = "application/json";
                    Console.WriteLine(client.UploadString("EchoWithPost", "\"bye\""));

                    Console.WriteLine("Press any key to terminate");
                    Console.ReadLine();
                }
            }
        }
コード例 #3
0
ファイル: KodiConnector.cs プロジェクト: david-ju/Watched
        public IEnumerable<TvShow> GetWatchedEpisodes()
        {
            var url = string.Format("http://{0}:{1}/jsonrpc", _host, _port);
            var tvShowRequest = JsonConvert.SerializeObject(new
            {
                jsonrpc = "2.0",
                method = "VideoLibrary.GetTVShows",
                id = 1,
                @params = new
                {
                    properties = new[] { "imdbnumber" }
                }
            });

            var episodesRequest = JsonConvert.SerializeObject(new
            {
                jsonrpc = "2.0",
                method = "VideoLibrary.GetEpisodes",
                id = 1,
                @params = new
                {
                    filter = new
                    {
                        field = "playcount",
                        @operator = "isnot",
                        value = "0"
                    },
                    properties = new[] { "tvshowid", "episode", "season" }
                }
            });

            using (var wc = new WebClient())
            {
                if (!string.IsNullOrEmpty(_username) && !string.IsNullOrEmpty(_password))
                {
                    string encoded = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(_username + ":" + _password));
                    wc.Headers.Add("Authorization", "Basic " + encoded);
                }
                var tvShowsResponse = (GetTvShowsResponse)JsonConvert.DeserializeObject(wc.UploadString(url, tvShowRequest), typeof(GetTvShowsResponse));

                var episodesResponse = (GetEpisodesResponse)JsonConvert.DeserializeObject(wc.UploadString(url, episodesRequest), typeof(GetEpisodesResponse));

                foreach (var tvShow in tvShowsResponse.Result.TvShows)
                {
                    tvShow.Episodes = episodesResponse.Result.Episodes.Where(e => e.TvShowId == tvShow.TvShowId);
                }

                return tvShowsResponse.Result.TvShows;
            }
        }
コード例 #4
0
        /// <summary>
        /// This method is called when any method on a proxied object is invoked.
        /// </summary>
        /// <param name="method">Information about the method being called.</param>
        /// <param name="args">The arguments passed to the method.</param>
        /// <returns>Result value from the proxy call</returns>
        public object OnMethod(MethodInfo method, object[] args)
        {
            if (args.Length != 1) throw new Exception("Only methods with one parameter can be used through REST proxies.");
            var data = args[0];

            if (_contractType == null)
            {
                var declaringType = method.DeclaringType;
                if (declaringType == null) throw new Exception("Can't detirmine declaring type of method '" + method.Name + "'.");
                if (declaringType.IsInterface)
                    _contractType = declaringType;
                else
                {
                    var interfaces = declaringType.GetInterfaces();
                    if (interfaces.Length != 1) throw new Exception("Can't detirmine declaring contract interface for method '" + method.Name + "'.");
                    _contractType = interfaces[0];
                }
            }

            var httpMethod = RestHelper.GetHttpMethodFromContract(method.Name, _contractType);
            var exposedMethodName = RestHelper.GetExposedMethodNameFromContract(method.Name, httpMethod, _contractType);

            try
            {
                using (var client = new WebClient())
                {
                    client.Headers.Add("Content-Type", "application/json; charset=utf-8");
                    string restResponse;
                    switch (httpMethod)
                    {
                        case "POST":
                            restResponse = client.UploadString(_serviceUri.AbsoluteUri + "/" + exposedMethodName, SerializeToRestJson(data));
                            break;
                        case "GET":
                            var serializedData = RestHelper.SerializeToUrlParameters(data);
                            restResponse = client.DownloadString(_serviceUri.AbsoluteUri + "/" + exposedMethodName + serializedData);
                            break;
                        default:
                            restResponse = client.UploadString(_serviceUri.AbsoluteUri + "/" + exposedMethodName, httpMethod, SerializeToRestJson(data));
                            break;
                    }
                    return DeserializeFromRestJson(restResponse, method.ReturnType);
                }
            }
            catch (Exception ex)
            {
                throw new CommunicationException("Unable to communicate with REST service.", ex);
            }
        }
コード例 #5
0
        public void Stubs_should_be_unique_within_context()
        {
            var wc = new WebClient();
            string stubbedReponseOne = "Response for first test in context";
            string stubbedReponseTwo = "Response for second test in context";

            IStubHttp stubHttp = _httpMockRepository.WithNewContext();

            stubHttp.Stub(x => x.Post("/firsttest")).Return(stubbedReponseOne).OK();

            stubHttp.Stub(x => x.Post("/secondtest")).Return(stubbedReponseTwo).OK();

            Assert.That(wc.UploadString("Http://localhost:8080/firsttest/", ""), Is.EqualTo(stubbedReponseOne));
            Assert.That(wc.UploadString("Http://localhost:8080/secondtest/", ""), Is.EqualTo(stubbedReponseTwo));
        }
コード例 #6
0
        public override IEnumerable<IFragment> GetFragments(DateTime since, DateTime before)
        {
            // format the query
            var sinceString = since.ToString("u");
            var sparqlQuery = string.Format(_fragmentsQuery, "\"" + sinceString + "\"^^<http://www.w3.org/2001/XMLSchema#date>");
            
            // make request
            var wc = new WebClient();
            wc.Headers.Add("Content-Type", "application/sparql-query");
            var result = XDocument.Parse(wc.UploadString(_sparqlEndpoint, sparqlQuery));
            
            // process the result
            foreach (var sparqlResultRow in result.SparqlResultRows())
            {
                var resource = sparqlResultRow.GetColumnValue("resource") as Uri;
                var updated = (DateTime) sparqlResultRow.GetColumnValue("updated");
                if (resource == null || updated == null) continue;

                yield return
                    new Fragment()
                        {
                            PublishDate = updated,
                            ResourceId = resource.AbsoluteUri,
                            ResourceName = resource.AbsoluteUri,
                            ResourceUri = resource.AbsoluteUri
                        };
            }
        }
コード例 #7
0
 public User GetUserDetailsFrom(string token)
 {
     User user = new User();
     string parameters = String.Format("apiKey={0}&token={1}&format=xml", ApplicationSettingsFactory.GetApplicationSettings().JanrainApiKey, token);
     string response;
     using (var w = new WebClient())
     {
         response = w.UploadString("https://rpxnow.com/api/v2/auth_info", parameters);
     }
     var xmlResponse = XDocument.Parse(response);
     var userProfile = (from x in xmlResponse.Descendants("profile")
                        select new
                        {
                            id = x.Element("identifier").Value,
                            email = (string)x.Element("email") ?? "No Email"
                        }).SingleOrDefault();
     if (userProfile != null)
     {
         user.AuthenticationToken = userProfile.id;
         user.Email = userProfile.email;
         user.IsAuthenticated = true;
     }
     else
         user.IsAuthenticated = false;
     return user;
 }
コード例 #8
0
ファイル: Program.cs プロジェクト: mattkur/KCSARA-Database
        static License GetLicense(string call)
        {
            WebClient client = new WebClient();
              client.Headers.Add(HttpRequestHeader.Referer, "http://wireless2.fcc.gov/UlsApp/UlsSearch/searchAmateur.jsp");
              client.Headers.Add(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");
              string linkPage = client.UploadString("http://wireless2.fcc.gov/UlsApp/UlsSearch/results.jsp", string.Format("fiUlsExactMatchInd=Y&fiulsTrusteeName=&fiOwnerName=&fiUlsFRN=&fiCity=&ulsState=&fiUlsZipcode=&ulsCallSign={0}&statusAll=Y&ulsDateType=&dateSearchType=+&ulsFromDate=&ulsToDate=3%2F8%2F2014&fiRowsPerPage=10&ulsSortBy=uls_l_callsign++++++++++++++++&ulsOrderBy=ASC&x=34&y=11&hiddenForm=hiddenForm&jsValidated=true", call));

              var match = Regex.Match(linkPage, "license.jsp(;JSESSIONID_ULSSEARCH=[a-zA-Z0-9!]+)?\\?licKey=(\\d+)", RegexOptions.IgnoreCase);
              if (!match.Success) return null;

              string url = "http://wireless2.fcc.gov/UlsApp/UlsSearch/license.jsp?licKey=" + match.Groups[2].Value;
              var page = client.DownloadString(url);

              var blockStart = page.IndexOf("<!--Addresses are displayed on successive lines:");
              var blockEnd = page.IndexOf("</td>", blockStart);
              var block = page.Substring(blockStart, blockEnd - blockStart);

             // match = Regex.Match(block, @"^ +([a-zA-Z ,\\-]+)\<br\>");
              match = Regex.Match(page, @"<title>ULS License \- Amateur License \- [A-Z0-9 ]+ \- ([^<]+)</title>");
              if (!match.Success) return null;

              License lic = new License { Name = match.Groups[1].Value };

              match = Regex.Match(page, @"Grant</td>\s+<td[^>]+>\s+([\d/]{10})", RegexOptions.Multiline);
              lic.Issued = DateTime.Parse(match.Groups[1].Value);

              match = Regex.Match(page, @"Expiration</td>\s+<td[^>]+>\s+([\d/]{10})", RegexOptions.Multiline);
              lic.Expires = DateTime.Parse(match.Groups[1].Value);

              lic.Url = url;

              return lic;
        }
コード例 #9
0
ファイル: Program.cs プロジェクト: jaya302sree/Learning
        static void Main(string[] args)
        {
            Thread t1 = new Thread(new ThreadStart(SimpleClientRequest));
            t1.Start();

            string result = "";
            Stock msft = new Stock("MSFT", 43.28);
            string jsonStr = JsonConvert.SerializeObject(msft);
            using (var client = new WebClient())
            {
                client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
                var data = "= " + jsonStr;
                result = client.UploadString("http://localhost:49703/api/stock", "POST", data);
                Console.WriteLine("Data posted to browser from main thread");
            }

            Stock msftupdate = new Stock("MSFT", 53.28);
            string jsonStrupdate = JsonConvert.SerializeObject(msftupdate);
            using (var client = new WebClient())
            {
                client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
                var data = "= " + jsonStrupdate;
                result = client.UploadString("http://localhost:49703/api/stock", "Put", data);
                Console.WriteLine("Data updated in browser from main thread");
            }

            using (var client = new WebClient())
            {
                WebRequest request = WebRequest.Create("http://localhost:49703/api/stock");
                request.Method = "DELETE";
                request.GetResponse();
                Console.WriteLine("Data deleted in browser from main thread");
            }
               // Console.ReadLine();
        }
コード例 #10
0
ファイル: ConnegFixture.cs プロジェクト: henninga/fubumvc
 public void SendToMirror(string contentType, string content)
 {
     var client = new WebClient();
     client.Headers.Add("content-type", contentType);
     _lastResponse = client.UploadString("http://localhost/fubu-testing/conneg/mirror", content);
     _lastResponseContentType = client.ResponseHeaders["content-type"];
 }
コード例 #11
0
 public void tokenProviderTokenExpired(object s, TokenExpiredEventArgs e) {
     var dic = new Dictionary<string, string>();
     dic.Add("client_id", ClientId);
     dic.Add("client_secret", ClientSecret);
     dic.Add("refresh_token", e.RefreshToken);
     dic.Add("scope", "cdr");
     dic.Add("grant_type", "refresh_token");
     
     string postData = "";
     string postDataSperator = "";
     foreach(var i in dic) {
         postData += string.Format("{0}{1}={2}", 
             postDataSperator, HttpUtility.UrlEncode(i.Key), HttpUtility.UrlEncode(i.Value));
         postDataSperator = "&";
     }
     using (WebClient client = new WebClient()) {
         string str = client.UploadString(Endpoints.Token, postData);
         if (string.IsNullOrEmpty(str)) {
             return;
         }
         JObject jsonResult = JObject.Parse(str);
         ((Token)s).SetAccessToken(jsonResult.GetValue("access_token").ToString());
         ((Token)s).SetRefreshToken(jsonResult.GetValue("refresh_token").ToString());
     }
 }
コード例 #12
0
ファイル: Recoder.cs プロジェクト: ufjl0683/wirelessBrocast
       public System.Collections.Generic.List<RecordInfo> GetRecordInfo(DateTime BeginTime)

       {

            
           WebClient client = new WebClient();
           client.Credentials = new NetworkCredential("vlansd", "1234");
           DateTime now=DateTime.Now;
           string param =string.Format( 
               "cDateTime=on&StartYear={0}&StartMonth={1}&StartDay={2}&StartHour={3}&StartMinute={4}&StartSecond={5}&StopYear={6}&StopMonth={7}&StopDay={8}&StopHour={9}&StopMinute={10}&StopSecond={11}&tCallerID=&tDTMF=&tRings=&tRecLength=",
               BeginTime.Year,BeginTime.Month,BeginTime.Day,BeginTime.Hour,BeginTime.Minute,BeginTime.Second,
               now.Year,now.Month,now.Day,now.Hour,now.Minute,now.Second
               );

           string res = client.UploadString("http://192.168.1.100/vlansys/vlaninquiry?",
               param);
           Regex regex = new Regex(@"RecLength=(\d+).*StartTime=(.*?),");
           MatchCollection collection = regex.Matches(res);

           System.Collections.Generic.List<RecordInfo> list = new List<RecordInfo>();
           for (int i = 0; i < collection.Count; i++)
           {
               list.Add(
                   new RecordInfo()
                   {
                       TimeStamp = DateTime.Parse(collection[i].Groups[2].Value),
                       RecordSeconds = int.Parse(collection[i].Groups[1].Value)
                   }
                   );
            //   Console.WriteLine(collection[i].Groups[2].Value);
           }
           return list;
       }
コード例 #13
0
ファイル: MiataruClient.cs プロジェクト: pereritob/hacs
		public List<MiataruLocation> GetLastLocationForDevice(String DeviceID, String ServerURL)
		{
			// run the request
			GetLocationRequest Request = new GetLocationRequest (DeviceID);

			// get the JSON representation
			string json = JsonConvert.SerializeObject(Request);

			// run a request and get the response...
			WebClient client = new WebClient ();

			client.Headers["Content-Type"] = "application/json";
            client.Headers.Add("user-agent", "hacs");

			string ReturnJSONValue = client.UploadString (ServerURL + "/GetLocation", json);

			GetLocationResponse Response = JsonConvert.DeserializeObject<GetLocationResponse>(ReturnJSONValue);
			if (Response.MiataruLocation != null) {

				if (Response.MiataruLocation [0] != null) {
					// there's something in there...
					return Response.MiataruLocation;
				} else
					return null;
			}
			return null;
		}
コード例 #14
0
ファイル: Program.cs プロジェクト: fryeware/OpsWorks
 static async Task doDELETE(OpsWorksServer serverObj)
 {
     string json = Newtonsoft.Json.JsonConvert.SerializeObject(serverObj);
     WebClient web = new WebClient();
     //web.UploadString("http://safeweb-wf1/OpsWorksApi/api/SessionHost?serverObj=" + json, "DELETE", json);
     web.UploadString("http://safeweb-wf1/OpsWorksApiDev/api/SessionHost?serverObj=" + json, "DELETE", json);
 }
コード例 #15
0
        private static void AddBlock()
        {
            const int refsToGen = 5000;
            //string jsonInput = "{\"blockId\":\"1\",\"refsList\":[\"1.ref\",\"2.ref\"]}";
            string jsonInput = "{\"blockId\":\"1\",\"refsList\":[";

            using (var client = new WebClient())
            {
                client.Headers["Content-type"] = "application/json";
                client.Encoding = Encoding.UTF8;

                for (int i = 0; i < refsToGen; i++)
                {
                    if (i > 0)
                    {
                        jsonInput += ",";
                    }

                    jsonInput += "\"" + i + ".ref\"";
                }

                jsonInput += "]}";
                var response = client.UploadString(BasePath + "block/update", "PUT", jsonInput);
            }
        }
コード例 #16
0
 public ActionResult Login(string username, string password)
 {
     ServicePointManager.ServerCertificateValidationCallback = OnServerCertificateValidationCallback;
     AuthResponse data;
     using (WebClient client = new WebClient())
     {
         var postData = JsonConvert.SerializeObject(new { username = username, password = password });
         client.Headers["User-Agent"] = PrivateConfig.UserAgent;
         client.Headers["Content-Type"] = "application/json; charset=utf-8";
         var rawData = client.UploadString(PrivateConfig.Authorization.Uri, postData);
         data = JsonConvert.DeserializeObject<AuthResponse>(rawData);
     }
     if (data != null && data.Success)
     {
         var session = new Session()
         {
             DisplayName = data.Name,
             Groups = data.Groups,
             Username = username
         };
         new SessionRepository().Collection.Insert(session);
         var cookie = new HttpCookie(CookieAuthenticatedAttribute.CookieName, session.Id);
         HttpContext.Response.Cookies.Clear();
         HttpContext.Response.Cookies.Add(cookie);
     }
     return JsonNet(data);
 }
コード例 #17
0
        static void Main()
        {
            DistanceCalculatorServiceClient service = new DistanceCalculatorServiceClient();

            var result = service.CalcDistance(new Point() {X = 1, Y = 2}, new Point() {X = 3, Y = 5});

            Console.WriteLine("Result from soap service: " + result);

            using (WebClient webClient = new WebClient())
            {
                var calcDistanceRequest = new CalculateDistanceRequest()
                {
                    StartPoint = new RESTServices.Models.Point
                    {
                        X = 3,
                        Y = 4
                    },
                    EndPoint = new RESTServices.Models.Point
                    {
                        X = 13,
                        Y = 21
                    }
                };

                webClient.Headers.Set("Content-type", "application/json");

                var distanceRequestAsJsonString = JsonConvert.SerializeObject(calcDistanceRequest);

                var response = webClient.UploadString("http://localhost:24084/Api/calculateDistance",
                    distanceRequestAsJsonString);

                Console.WriteLine();
                Console.WriteLine("Result from web service: " + response);
            }
        }
コード例 #18
0
ファイル: TraktAPI.cs プロジェクト: bjarkimg/MPExtended
        private static string CallAPI(string address, string data)
        {
            WebClient client = new WebClient();
            try
            {
                ServicePointManager.Expect100Continue = false;
                client.Encoding = Encoding.UTF8;
                client.Headers.Add("User-Agent", TraktConfig.UserAgent);
                return client.UploadString(address, data);
            }
            catch (WebException e)
            {
                // this might happen in the TestAccount method
                if ((e.Response as HttpWebResponse).StatusCode == HttpStatusCode.Unauthorized)
                {
                    using (var reader = new StreamReader(e.Response.GetResponseStream()))
                    {
                        return reader.ReadToEnd();
                    }
                }

                Log.Warn("Failed to call Trakt API", e);
                return String.Empty;
            }
        }
コード例 #19
0
ファイル: HttpServerLoadTests.cs プロジェクト: kow/Aurora-Sim
        private static void OnSendRequest(object state)
        {
            string id = state.ToString().PadLeft(3, '0');
            WebClient client = new WebClient();

            Interlocked.Increment(ref _currentThreadCount);
            if (_currentThreadCount == ThreadCount)
                _threadsGoEvent.Set();
            
            // thread should wait until all threads are ready, to try the server.
            if (!_threadsGoEvent.WaitOne(60000, true))
                Assert.False(true, "Start event was not triggered.");

            try
            {
                client.UploadString(new Uri("http://localhost:8899/?id=" + id), "GET");
            }
            catch(WebException)
            {
                _failedThreads.Add(id);
            }
            Console.WriteLine(id + " done, left: " + _currentThreadCount);

            // last thread should signal main test
            Interlocked.Decrement(ref _currentThreadCount);
            if (_currentThreadCount == 0)
                _threadsDoneEvent.Set();
        }
コード例 #20
0
ファイル: Publish.cs プロジェクト: frankmeola/BuildExtensions
        public override bool Execute()
        {
            var result = false;

            try
            {
                Log.LogMessage("Sitecore Ship Publish Start: {0} | {1} | {2} | {3} | {4}", HostName, Mode, Source, Targets, Languages);

                 HostName = HostName.TrimEnd('/');
                string absolutUrl = string.Format("{0}{1}", HostName, string.Format(Path, Mode));

                string formData = string.Format("source={0}&targets={1}&languages={2}",
                    HttpUtility.UrlEncode(Source),
                    HttpUtility.UrlEncode(Targets),
                    HttpUtility.UrlEncode(Languages)
                    );

                WebClient client = new WebClient();
                client.UploadString(absolutUrl, "POST", formData);

                result = true;

                Log.LogMessage("Sitecore Ship Publish Finished: {0} | {1} | {2} | {3} | {4}", HostName, Mode, Source, Targets, Languages);

            }
            catch (Exception ex)
            {
                Log.LogErrorFromException(ex, true);
            }

            return result;
        }
コード例 #21
0
ファイル: Program.cs プロジェクト: windrobin/kumpro
        static void Main(String[] args) {
            try {
                String fp = null;
                bool fSetup = false;
                foreach (String arg in args) {
                    if (arg.StartsWith("/")) {
                        if (arg == "/setup")
                            fSetup = true;
                    }
                    else if (fp == null) fp = arg;
                }

                if (fSetup || fp == null) {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new NForm());
                }
                else {
                    try {
                        WebClient wc = new WebClient();
                        String res = wc.UploadString(fp, "");

                        appTrace.TraceEvent(TraceEventType.Information, (int)EvID.Sent, "送信しました。結果: " + res);
                    }
                    catch (Exception err) {
                        appTrace.TraceEvent(TraceEventType.Error, (int)EvID.Exception, "送信に失敗: " + err);
                        appTrace.Close();
                        Environment.Exit(1);
                    }
                }
            }
            finally {
                appTrace.Close();
            }
        }
コード例 #22
0
        protected override IEnumerable<Product> GetStoreProducts(string cardName, string comparisonCardName, string searchExpression)
        {
            string searchUrl = _searchUrl;
            string searchData = _searchData.Replace("<term>", Uri.EscapeDataString(searchExpression).Replace("%C3%A6", "%E6")); // Aether Fix

            List<Product> products = new List<Product>();

            int page = 1;
            bool foundItems;
            do
            {
                foundItems = false;

                string content;
                using (WebClient wc = new WebClient())
                {
                    wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
                    content = wc.UploadString(searchUrl, searchData.Replace("<page>", page.ToString()));
                    page++;
                }

                HtmlDocument doc = new HtmlDocument();
                doc.LoadHtml(content);

                foreach (HtmlNode productLi in doc.DocumentNode.SelectNodes("//li"))
                {
                    HtmlNode namePar = productLi.SelectSingleNode("div[@class='card_name']/p[@class='ingles']");
                    HtmlNode nameLink = productLi.SelectSingleNode("div[@class='card_name']/p[@class='portugues font_GBlack']/a");
                    HtmlNode priceSpan = productLi.SelectSingleNode("p[@class='valor']/span[@class='vista']");
                    HtmlNode actionsPar = productLi.SelectSingleNode("p[@class='estoque']");

                    if (namePar != null)
                    {
                        foundItems = true;

                        string name = NormalizeCardName(namePar.InnerText).Replace("&#198;", "ae"); // Aether fix
                        string url = nameLink.Attributes["href"].Value;

                        string currency = "BRL";
                        double price = 0;
                        if (priceSpan.InnerText.Length > 0) price = double.Parse(priceSpan.InnerText.Replace("R$", "").Trim(), new CultureInfo("pt-BR"));
                        bool available = actionsPar.InnerHtml.IndexOf("quantidade em estoque") >= 0;

                        if (name.ToUpperInvariant() == NormalizeCardName(comparisonCardName).ToUpperInvariant())
                        {
                            products.Add(new Product()
                            {
                                Name = cardName,
                                Price = price,
                                Currency = currency,
                                Available = available,
                                Url = url
                            });
                        }
                    }
                }
            } while (foundItems);

            return (products);
        }
コード例 #23
0
ファイル: WNSMethods.cs プロジェクト: nogsus/LiveSDK
        private void AutenticateWNS()
        {
            try
            {
                // get an access token
                var urlEncodedSid = HttpUtility.UrlEncode(String.Format("{0}", this.Sid));
                var urlEncodedSecret = HttpUtility.UrlEncode(this.Secret);

                var uri =
                  String.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=notify.windows.com",
                  urlEncodedSid,
                  urlEncodedSecret);

                var client = new WebClient();
                client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                string response = client.UploadString("https://login.live.com/accesstoken.srf", uri);

                // parse the response in JSON format
                OAuthToken token;
                using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(response)))
                {
                    var ser = new DataContractJsonSerializer(typeof(OAuthToken));
                    token = (OAuthToken)ser.ReadObject(ms);
                }
                this.accessToken = token.AccessToken;
            }
            catch (Exception ex)
            {
                //lblResult.Text = ex.Message;
                //lblResult.ForeColor = System.Drawing.Color.Red;
                throw ex;
            }
        }
コード例 #24
0
        private void buttonIdentify_Click(object sender, EventArgs e)
        {
            WebClient wc = new WebClient();
              wc.Proxy = mainClass.GetProxy();
              wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

              string result = "Bad API request, no result";
              try {
            result = wc.UploadString("http://" + "pastebin.com/api/api_login.php", "api_dev_key=" + mainClass.PastebinAPIKey + "&api_user_name=" + Uri.EscapeDataString(textUsername.Text) + "&api_user_password="******"Bad API request, ")) {
            if (result.Length == 32) {
              mainClass.settings.SetString("UserKey", result);
              mainClass.settings.SetString("UserName", textUsername.Text);
              mainClass.settings.Save();

              mainClass.UserLoggedIn = true;
              mainClass.UserKey = result;

              textUsername.Text = "";
              textPassword.Text = "";
              buttonIdentify.Enabled = false;
            } else
              MessageBox.Show("Unexpected response: \"" + result + "\"");
              } else
            MessageBox.Show("Error: " + result.Split(new string[] { ", " }, StringSplitOptions.None)[1]);
        }
コード例 #25
0
 protected override string QueryAccessToken(Uri returnUrl, string authorizationCode) {
     var dic = new Dictionary<string, string>();
     dic.Add("client_id", ClientId);
     dic.Add("redirect_uri", returnUrl.AbsoluteUri);
     dic.Add("client_secret", ClientSecret);
     dic.Add("code", authorizationCode);
     dic.Add("scope", "cdr");
     dic.Add("grant_type", "authorization_code");
     
     string postData = "";
     string postDataSperator = "";
     foreach(var i in dic) {
         postData += string.Format("{0}{1}={2}", 
             postDataSperator, HttpUtility.UrlEncode(i.Key), HttpUtility.UrlEncode(i.Value));
         postDataSperator = "&";
     }
     using (WebClient client = new WebClient()) {
         string str = client.UploadString(Endpoints.Token, postData);
         if (string.IsNullOrEmpty(str)) {
             return null;
         }
         JObject jsonResult = JObject.Parse(str);
         return jsonResult.GetValue("access_token").ToString();
     }
 }
コード例 #26
0
        private Token QueryAccessTokens(string authorizationCode) {
            var dic = new Dictionary<string, string>();
            dic.Add("client_id", ClientId);
            dic.Add("redirect_uri", "urn:ietf:wg:oauth:2.0:oob");
            dic.Add("client_secret", ClientSecret);
            dic.Add("code", authorizationCode);
            dic.Add("scope", "cdr");
            dic.Add("grant_type", "authorization_code");
            
            string postData = "";
            string postDataSperator = "";
            foreach(var i in dic) {
                postData += string.Format("{0}{1}={2}", 
                    postDataSperator, HttpUtility.UrlEncode(i.Key), HttpUtility.UrlEncode(i.Value));
                postDataSperator = "&";
            }
            using (WebClient client = new WebClient()) {
                string str = client.UploadString(Endpoints.Token, postData);
                if (string.IsNullOrEmpty(str)) {
                    return null;
                }
                JObject jsonResult = JObject.Parse(str);

                var token = new Token(
                    jsonResult.GetValue("access_token").ToString(), jsonResult.GetValue("refresh_token").ToString());

                token.TokenExpired += tokenProviderTokenExpired;

                return token;
            }
        }
コード例 #27
0
        /// <summary>
        /// Creates a string using messageformat.js.
        /// </summary>
        /// <param name="language">
        /// The language to use.
        /// <example>
        /// <para>
        /// language: en-EN OR en-US OR es-ES
        /// </para>
        /// </example>
        /// </param>
        /// <param name="formattedMessage">
        /// A messageformat formatted message.
        /// <example>
        /// <para>
        /// formattedMessage: {GENDER, select, male {He} female {She} other {They}} found it!
        /// </para>
        /// </example>
        /// </param>
        /// <param name="data">
        /// The data used to create the final string.
        /// <example>
        /// <para>
        /// data: {"GENDER": "male"}
        /// </para>
        /// </example>
        /// </param>
        /// <returns></returns>
        public override string GenerateString(string language, string formattedMessage, string data)
        {
            formattedMessage = formattedMessage.Replace(Environment.NewLine, "");
            var wc = new WebClient();
            wc.Headers["Content-Type"] = "application/json";

            string format = String.Format(NodeJsEngine._nodeJsonRequestFormat, language, formattedMessage, data);

            // TODO make this an exponential back-off
            int delay = 5;
            for (int i = 0; i < NodeJsEngine._nodeJsonRequestRetries; i++)
            {
                try
                {
                    return wc.UploadString(this.NodeServer, "POST", format);
                }
                catch (Exception)
                {
                    if (i == NodeJsEngine._nodeJsonRequestRetries - 1)
                        throw;

                    Thread.Sleep(delay);
                    delay = (int) (delay*2.5);
                }
            }

            return null;
        }
コード例 #28
0
ファイル: Program.cs プロジェクト: s7loves/mypowerscgl
        static void test() {
            var client = new WebClient();
            System.Threading.Thread.Sleep(1000);
            client.Headers.Add("content-type", "application/xml");
            ////var user1 = client.DownloadString("http://localhost:3274/Member.svc/User/1");
            var user2 = client.DownloadString("http://192.168.238.129:82/AccountService/GetAccountData");
            Console.WriteLine(user2);

            //client.Headers.Add("content-type", "application/json;charset=utf-8");


            //var usern = client.UploadString("http://localhost:3274/Member.svc/User/admin/admin", "POST", String.Empty);
            //var usern = client.UploadString("http://localhost:3274/Member.svc/AddUser", "POST", user1);
            //var usern2 = client.UploadString("http://192.168.238.129:82/AccountService/SetList", "POST", user2);
            //Console.WriteLine(usern2);
            //var usern2 = "{\"Name\":\"rabbit\",\"Birthday\":\"\\/Sun Jul 03 13:25:54 GMT+00:00 2011\\/\",\"Age\":56,\"Address\":\"YouYi East Road\"}";
            string usern2 = "{\"Address\":\"YouYi East Road\",\"Age\":56,\"Birthday\":\"\\/Date(1320822727963+0800)\\/\",\"Name\":\"rabbit\"}";
            //usern2 = "{\"Address\":\"YouYi East Road\",\"Age\":56,\"Birthday\":\"\\/Date(1320822727963+0800)\\/\",\"Name\":\"rabbit\"}";
            client.Headers.Add("content-type", "application/json;charset=utf-8");
            usern2 = client.UploadString("http://192.168.238.129:82/AccountService/SetData", "POST", usern2);
            //client.Headers.Add("content-type", "application/json;charset=utf-8");
            //var data = "{\"gtID\":\"21803701400030000\",\"LineCode\":\"2180370140003\",\"gtCode\":\"21803701400030000\",\"gth\":\"0000\",\"gtType\":\"混凝土拔梢杆\",\"gtModle\":\"直线杆\",\"gtHeight\":\"10.0\",\"gtLon\":\"127.00069166666667\",\"gtLat\":\"46.94825\",\"gtElev\":\"160.3\",\"gtSpan\":\"否\",\"jsonData\":null}";//,{"gtID":"21803701400030010","LineCode":"2180370140003","gtCode":"21803701400030010","gth":"0010","gtType":"混凝土拔梢杆","gtModle":"直线杆","gtHeight":"10.0","gtLon":"127.001175","gtLat":"46.94802333333333","gtElev":"159.7","gtSpan":"否","jsonData":null}]";
            
            //data = "[{\"gth\":\"0010\",\"gtHeight\":\"10.0\",\"gtLat\":\"0\",\"gtID\":\"20110815101847123555\",\"gtType\":\"混凝土拔梢杆\",\"gtSpan\":\"否\",\"gtLon\":\"0\",\"LineCode\":\"2180370010003001\",\"gtCode\":\"21803700100030010010\",\"gtModle\":\"直线杆\",\"gtElev\":\"0\"},{\"gth\":\"0020\",\"gtHeight\":\"10.0\",\"gtLat\":\"0\",\"gtID\":\"20110815101847123556\",\"gtType\":\"混凝土拔梢杆\",\"gtSpan\":\"否\",\"gtLon\":\"0\",\"LineCode\":\"2180370010003001\",\"gtCode\":\"21803700100030010020\",\"gtModle\":\"直线杆\",\"gtElev\":\"0\"}]";
            //var usern2 = client.UploadString(baseUrl + "/UpdateGtOne", "POST", data);


            Console.WriteLine(usern2);


        }
コード例 #29
0
    /// <summary>
    /// post数据到指定接口并返回数据
    /// </summary>
    public string PostXmlToUrl(string url, string postData)
    {
        string returnmsg = "";

        using (System.Net.WebClient wc = new System.Net.WebClient())
        {
            returnmsg = wc.UploadString(url, "POST", postData);
        }
        return(returnmsg);
    }
コード例 #30
0
 public FederateRecordSet GetFederateInfo()
 {
     if (ViewState["Federates"] == null)
     {
         System.Net.WebClient wc = new System.Net.WebClient();
         string federatedata     = wc.UploadString("http://3dr.adlnet.gov/federation/3DR_Federation_Mgmt.svc/GetAllFederates", "POST", "");
         federates = (new JavaScriptSerializer()).Deserialize <FederateRecordSet>(federatedata);
         ViewState["Federates"] = federates;
     }
     return(ViewState["Federates"] as FederateRecordSet);
 }
コード例 #31
0
ファイル: Global.cs プロジェクト: phiree/Quartz2Demo
    // keep site live.
    public static void _SetupRefreshJob()
    {
        string refreshUrl = "http://localhost:19213//?refreshid=" + Guid.NewGuid();
        Action remove     = null;

        if (HttpContext.Current != null)
        {
            remove = HttpContext.Current.Cache["Refresh"] as Action;
        }
        if (remove is Action)
        {
            HttpContext.Current.Cache.Remove("Refresh");
            remove.EndInvoke(null);
        }

        //get the worker
        Action work = () =>
        {
            while (true)
            {
                System.Threading.Thread.Sleep(1000 * 60 * 1);
                System.Net.WebClient refresh = new System.Net.WebClient();
                try
                {
                    refresh.UploadString(refreshUrl, string.Empty);
                }
                catch (Exception ex)
                {
                }
                finally
                {
                    refresh.Dispose();
                }
            }
        };


        work.BeginInvoke(null, null);

        //add this job to the cache
        if (HttpContext.Current != null)
        {
            HttpContext.Current.Cache.Add(
                "Refresh",
                work,
                null,
                Cache.NoAbsoluteExpiration,
                Cache.NoSlidingExpiration,
                CacheItemPriority.Normal,
                (s, o, r) => { _SetupRefreshJob(); }
                );
        }
    }
コード例 #32
0
        public HttpResponseMessage PutTunnel(Detalle_de_Ingredientes emp, string user, string password)
        {
            var client = new System.Net.WebClient();

            client.Headers = TokenManager.GetAuthenticationHeader(user, password);
            client.Headers["Content-Type"] = "application/json";
            var dataString = new JavaScriptSerializer().Serialize(emp);

            var result = client.UploadString(new Uri(baseApi + ApiControllerUrl + "/Put?Id=" + emp.Clave), "PUT"
                                             , dataString);

            return(Request.CreateResponse(HttpStatusCode.OK, result, Configuration.Formatters.JsonFormatter));
        }
コード例 #33
0
        public string Authorize(string channelName, string socketId)
        {
            string authToken = null;

            using (var webClient = new System.Net.WebClient())
            {
                string data = String.Format("channel_name={0}&socket_id={1}", channelName, socketId);
                webClient.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
                authToken = webClient.UploadString(_authEndpoint, "POST", data);
            }

            return(authToken);
        }
コード例 #34
0
        public static string Post(string url, ListUtility.Parameters parameters)
        {
            string sParameters = ConvertParameter(parameters);
            string htmlResult;

            using (System.Net.WebClient wc = new System.Net.WebClient())
            {
                wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
                htmlResult = wc.UploadString(url, sParameters);
            }

            return(htmlResult);
        }
コード例 #35
0
        public static string Post(string url, string json)
        {
            string sParameters = json;
            string htmlResult;

            using (System.Net.WebClient wc = new System.Net.WebClient())
            {
                wc.Headers[HttpRequestHeader.ContentType] = "application/json";
                htmlResult = wc.UploadString(url, sParameters);
            }

            return(htmlResult);
        }
コード例 #36
0
        public HttpResponseMessage PostTunnel(MS_Equipamiento_Alterno_Ejercicios emp, string user, string password)
        {
            var client = new System.Net.WebClient();

            client.Headers = TokenManager.GetAuthenticationHeader(user, password);

            client.Headers["Content-Type"] = "application/json";
            var dataString = new JavaScriptSerializer().Serialize(emp);

            var result = client.UploadString(new Uri(baseApi + ApiControllerUrl + "/Post"), "POST",
                                             dataString);

            return(Request.CreateResponse(HttpStatusCode.OK, result, Configuration.Formatters.JsonFormatter));
        }
コード例 #37
0
 //Sending post,put,delete
 private string SendRequest(string conString, string httpMethod, string data)
 {
     try
     {
         using (var client = new System.Net.WebClient())
         {
             return(client.UploadString(conString, httpMethod, data));
         }
     }
     catch (WebException e)
     {
         return(e.Message);
     }
 }
コード例 #38
0
 public string Post(string url, object data, JsonSerializerSettings settings = null)
 {
     System.Net.WebClient client = createWebClient();
     try
     {
         string json = JsonConvert.SerializeObject(data, settings);
         return(client.UploadString(url, "POST", json));
     }
     catch
     {
         // Für Diagnosezwecke wird hier gefangen und weitergeworfen
         throw;
     }
 }
コード例 #39
0
    public Dictionary <string, object> CallAPI(string cmd, SortedList <string, string> parms = null)
    {
        if (parms == null)
        {
            parms = new SortedList <string, string>();
        }
        parms["version"] = "1";
        parms["key"]     = s_pubkey;
        parms["cmd"]     = cmd;

        string post_data = "";

        foreach (KeyValuePair <string, string> parm in parms)
        {
            if (post_data.Length > 0)
            {
                post_data += "&";
            }
            post_data += parm.Key + "=" + Uri.EscapeDataString(parm.Value);
        }

        byte[] keyBytes   = encoding.GetBytes(s_privkey);
        byte[] postBytes  = encoding.GetBytes(post_data);
        var    hmacsha512 = new System.Security.Cryptography.HMACSHA512(keyBytes);
        string hmac       = BitConverter.ToString(hmacsha512.ComputeHash(postBytes)).Replace("-", string.Empty);

        // do the post:
        System.Net.WebClient cl = new System.Net.WebClient();
        cl.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
        cl.Headers.Add("HMAC", hmac);
        cl.Encoding = encoding;

        var ret = new Dictionary <string, object>();

        try
        {
            string resp    = cl.UploadString("https://www.coinpayments.net/api.php", post_data);
            var    decoder = new System.Web.Script.Serialization.JavaScriptSerializer();
            ret = decoder.Deserialize <Dictionary <string, object> >(resp);
        }
        catch (System.Net.WebException e)
        {
            ret["error"] = "Exception while contacting CoinPayments.net: " + e.Message;
        }
        catch (Exception e)
        {
            ret["error"] = "Unknown exception: " + e.Message;
        }
        return(ret);
    }
コード例 #40
0
        private string Post(string postData)
        {
            System.Text.Encoding enc =
                System.Text.Encoding.GetEncoding("shift_jis");

            System.Net.WebClient wc = new System.Net.WebClient();
            wc.Encoding = enc;
            wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            string resText = wc.UploadString(serverUrl, postData);

            wc.Dispose();

            return(resText);
        }
コード例 #41
0
ファイル: Test.cs プロジェクト: jbtxwd/CompareCoin
    public string UserRequest(string api, Dictionary <string, string> datas = null)
    {
        if (datas == null)
        {
            datas = new Dictionary <string, string>();
        }

        string nonce = Token.GetNonce();

        datas.Add("nonce", nonce);
        datas.Add("key", pub_key);

        int    i   = 0;
        string msg = "";

        foreach (KeyValuePair <string, string> data in datas)
        {
            if (i == 0)
            {
                msg += data.Key + "=" + data.Value;
            }
            else
            {
                msg += "&" + data.Key + "=" + data.Value;
            }
            i++;
        }

        string md5       = Token.GetMD5(_privateKey);//ok
        string signature = Token.CreateToken(msg, md5).ToLower();

        datas.Add("signature", signature);
        Post(api, datas);
        System.Net.WebClient wc = new System.Net.WebClient();
        wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
        var    url   = "https://www.jubi.com/api/v1/" + api;
        string param = msg + "&signature=" + signature;

        try
        {
            var info = wc.UploadString(url, param);
            Debug.Log(Time.time);
            return(info);
        }
        catch
        {
            return("{\"error\":\"api error\"}");
        }
    }
コード例 #42
0
        public String Post(String strUrl, StringBuilder sbXml)
        {
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback
                                                                      (
                delegate { return(true); }
                                                                      );

            String strRetorno = String.Empty;

            System.Net.WebClient wcService = new System.Net.WebClient();

            try
            {
                if (_Usuario != String.Empty && _Clave != String.Empty)
                {
                    wcService.Credentials = new System.Net.NetworkCredential(_Usuario, _Clave);
                    wcService.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(_Usuario + ":" + _Clave)));
                }

                wcService.Headers.Add("Method", _Method);
                wcService.Headers.Add("Content-Type", _ContentType);
                wcService.Headers.Add("Accept", _Accept);

                if (_SoapAction != String.Empty)
                {
                    wcService.Headers.Add("SOAPAction", _SoapAction);
                }

                wcService.Encoding = System.Text.Encoding.UTF8;

                if (sbXml.ToString().Trim() == String.Empty)
                {
                    strRetorno = wcService.DownloadString(strUrl);
                }
                else
                {
                    strRetorno = wcService.UploadString(strUrl, sbXml.ToString());
                }

                wcService.Dispose();
            }
            catch (Exception ex)
            {
                strRetorno = ex.Message;
                wcService.Dispose();
            }

            return(strRetorno);
        }
コード例 #43
0
ファイル: PlexUtils.cs プロジェクト: UnhealthyKraken/PlexWalk
        public static string doMetaLogin(RootFormInterface rfi)
        {
            var args = rfi.GetLaunchArgs();

            using (WebClient wc = new System.Net.WebClient())
            {
                string  parseME = null;
                Boolean fail    = false;
                do
                {
                    try
                    {
                        if (!fail && args.ContainsKey("username") && args.ContainsKey("password"))
                        {
                            doLoginFromCLI(wc, rfi);
                        }
                        else
                        {
                            Login loginform = new Login();
                            loginform.ShowDialog();
                            if (loginform.DialogResult == System.Windows.Forms.DialogResult.Cancel)
                            {
                                rfi.CloseForm();
                                return(parseME);
                            }
                            if (loginform.XmlUri == null)
                            {
                                wc.Credentials = loginform.creds;
                                wc.Headers[HttpRequestHeader.Authorization] = string.Format("Basic {0}", loginform.headerAuth);
                                rfi.SetRefreshMethod(RefreshMethod.Login);
                            }
                            else
                            {
                                return(doServerXmlLogin(loginform.XmlUri, rfi));
                            }
                        }
                        parseME = wc.DownloadString("https://plex.tv/pms/servers.xml");
                        wc.Headers["X-Plex-Client-Identifier"] = Descriptor.GUID;
                        Descriptor.myToken = parseLogin(wc.UploadString("https://plex.tv/users/sign_in.xml", String.Empty));
                        fail = false;
                    }
                    catch (Exception)
                    {
                        fail = true;
                    }
                } while (fail);
                return(parseME);
            }
        }
コード例 #44
0
    /// <summary>
    /// Post Api 返回结果文本
    /// </summary>
    /// <param name="apiUrl"></param>
    /// <param name="queryParams"></param>
    /// <param name="body"></param>
    /// <param name="token"></param>
    /// <returns></returns>
    public String Post(string apiUrl, Hashtable queryParams, JObject body, String token)
    {
        System.Net.WebClient webClientObj = CreateWebClient(token);

        apiUrl = FormatUrl(apiUrl, queryParams);
        try
        {
            String result = webClientObj.UploadString(apiUrl, "POST", body.ToString(Newtonsoft.Json.Formatting.None));
            return(result);
        }
        catch (Exception ce)
        {
            return(WhenError(ce));
        }
    }
コード例 #45
0
        public void PerformanceUploadTest()
        {
            if (System.IO.File.Exists(System.Windows.Forms.Application.StartupPath + "\\uploadspeed.txt"))
            {
                dBaselineUploadSpeed = double.Parse(System.IO.File.ReadAllText(System.Windows.Forms.Application.StartupPath + "\\uploadspeed.txt"));
            }
            else
            {
                System.Net.WebClient wc = new System.Net.WebClient();

                string sTemplate = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";

                int    iMax  = 5427880;
                string sData = "";
                for (int iOne = 0; iOne < iMax; iOne = iOne + 100000)
                {
                    sData += sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate;
                    sData += sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate;
                    sData += sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate;
                    sData += sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate;
                    sData += sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate;
                    sData += sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate;
                    sData += sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate;
                    sData += sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate;
                    sData += sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate;
                    sData += sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate + sTemplate;
                }

                string tempName = System.IO.Path.GetTempFileName();

                double starttime = Environment.TickCount;

                wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";
                string response = wc.UploadString("http://www.ozspeedtest.com/bandwidth-test/upload", "submit=Run+Upload+Test+%3E%3E%3E&st=1411533974672&conType=7&data=" + sData.Length.ToString() + "&0=" + sData);

                double stoptime = Environment.TickCount;

                double secs  = Math.Floor(stoptime - starttime) / 1000;
                double sec2  = Math.Round(secs);
                double kbsec = Math.Round(1024 / secs);

                dBaselineUploadSpeed = kbsec;

                System.IO.File.WriteAllText(System.Windows.Forms.Application.StartupPath + "\\uploadspeed.txt", dBaselineUploadSpeed.ToString());

                System.IO.File.Delete(tempName);
            }
        }
コード例 #46
0
        public String Post(string apiUrl, JObject body)
        {
            System.Net.WebClient webClientObj = CreateWebClient(DefaultToken);

            // apiUrl = FormatUrl(apiUrl, queryParams);
            try
            {
                webClientObj.Headers[HttpRequestHeader.ContentType] = "application/json";
                String result = webClientObj.UploadString(apiUrl, "POST", body.ToString(Newtonsoft.Json.Formatting.None));
                return(result);
            }
            catch (Exception ce)
            {
                return(WhenError(ce));
            }
        }
コード例 #47
0
    private String _Delete(string apiUrl, Hashtable queryParams, String token)
    {
        System.Net.WebClient webClientObj = CreateWebClient(token);

        apiUrl = FormatUrl(apiUrl, queryParams);

        try
        {
            String result = webClientObj.UploadString(apiUrl, "DELETE", "");
            return(result);
        }
        catch (Exception ce)
        {
            return(WhenError(ce));
        }
    }
コード例 #48
0
        private static bool ExecuteWebAPIRequest_InsertAllExpenses_ToMongoDB(string apiUrl, List <ExpenseJSON> expenses)
        {
            bool isDeleted = false;

            try
            {
                System.Net.WebClient client = InitializeWebClient();
                string json = JsonConvert.SerializeObject(expenses);
                isDeleted = bool.Parse(client.UploadString(apiUrl, json));//InsertAll
            }
            catch (Exception ex)
            {
                Console.WriteLine("ERROR !!!!!!!!!!!!!! :::: " + ex.ToString());
                Console.ReadLine();
            }
            return(isDeleted);
        }
コード例 #49
0
 public static string ApiServer(ApiServerAct Actione, ApiServerOutFormat Formate = ApiServerOutFormat.@string, string JsonData = "")
 {
     try
     {
         using (var client = new System.Net.WebClient())
         {
             string json = "{\"token\":\"ynWOXOWBviuL8QQDbYFcLi8wm2G1u3N0\",\"app\":\"TwitchBot\",\"version\":\"" +
                           Version + "\"" + JsonData + ",\"streamer\":\"" + MySave.Current.Streamer + "\"}";
             client.Encoding = Encoding.UTF8;
             return(client.UploadString("https://wsxz.ru/api/" + Actione.ToString() + "/" + Formate.ToString(), json));
         }
     }
     catch
     {
         return("Error(Api unavailable)");
     }
 }
コード例 #50
0
        /// <summary>
        /// 删除群发消息(删除消息只是将消息的图文详情页失效,已经收到的用户,还是能在其本地看到消息卡片)
        /// </summary>
        /// <param name="msg_id">群发的消息ID</param>
        /// <param name="errorDescription">描述</param>
        /// <returns>返回成功:true 失败:false</returns>
        public static bool DeleteMassSendMessage(string msg_id, ref string errorDescription)
        {
            errorDescription = "";

            if (string.IsNullOrEmpty(msg_id))
            {
                errorDescription = "-10007,消息ID能为空";
                return(false);
            }

            if (Shove._Convert.StrToLong(msg_id, -1) < 0)
            {
                errorDescription = "-10008,不合法的msg_id";
                return(false);
            }

            string json = "{\"msgid\":" + msg_id + "}";

            using (System.Net.WebClient client = new System.Net.WebClient())
            {
                client.Headers["Content-Type"] = "application/json";
                client.Encoding = System.Text.Encoding.UTF8;

                try
                {
                    string strResult = client.UploadString
                                           (string.Format("https://api.weixin.qq.com//cgi-bin/message/mass/delete?access_token={0}", Utility.Access_token), "post", json);
                    string errorCode = Utility.AnalysisJson(strResult, "errcode");

                    if (!errorCode.Equals("0"))
                    {
                        errorDescription = ErrorInformation.GetErrorCode(strResult, "errcode");
                        return(false);
                    }
                }
                catch (Exception ex)
                {
                    errorDescription = ex.Message;
                    return(false);
                }

                return(true);
            }
        }
コード例 #51
0
ファイル: LoginBase.cs プロジェクト: zwkjgs/LebiShop
        public string Post(string WebUrl, string json)
        {
            string content = "";

            try
            {
                //调用Main_Execute,并且获取其输出
                StringWriter         sw  = new StringWriter();
                string               url = WebUrl;
                System.Net.WebClient wc  = new System.Net.WebClient();
                wc.Encoding = System.Text.Encoding.UTF8;
                content     = wc.UploadString(WebUrl, "POST", json);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(content);
        }
コード例 #52
0
        public Jugadores Post(Jugadores jugador)
        {
            try
            {
                JugadoresPost jugadoresPost = new JugadoresPost()
                {
                    UserName = jugador.UserName,
                    Personas = new PersonasPost()
                    {
                        JugadoresId       = 1,
                        Apellido          = jugador.Personas.Apellido,
                        Nombre            = jugador.Personas.Nombre,
                        Pais              = jugador.Personas.Pais,
                        Provincia         = jugador.Personas.Provincia,
                        Cuidad            = jugador.Personas.Cuidad,
                        CorreoElectronico = jugador.Personas.CorreoElectronico,
                        FechaNacimiento   = jugador.Personas.FechaNacimiento,
                        Sexo              = jugador.Personas.Sexo,
                        Documento         = jugador.Personas.Documento
                    },
                    Patologia = jugador.Patologia
                };


                string json;

                var jugadoresJson = JsonConvert.SerializeObject(jugadoresPost);

                using (var webClient = new System.Net.WebClient())
                {
                    webClient.Headers[HttpRequestHeader.ContentType] = "application/json";

                    json = webClient.UploadString(url, jugadoresJson);
                }
                var jugadoresGet = JsonConvert.DeserializeObject <Jugadores>(json);

                return(jugadoresGet);
            }
            catch (Exception ex)
            {
                return(new Jugadores());
            }
        }
コード例 #53
0
        public static Dictionary <String, Object> Validate(string EncodedResponse, basePortalModule baseModule)
        {
            JavaScriptSerializer        jsSerializer    = new JavaScriptSerializer();
            Dictionary <String, Object> captchaResponse = new Dictionary <string, Object>();



            string PrivateKey = baseModule.ViewSettingT <String>("PowerForms_Recaptcha_v3_SecretKey", "");

            try
            {
                using (var client = new System.Net.WebClient())
                {
                    client.Headers[System.Net.HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";

                    //if (baseModule.IsSSL)
                    //{
                    //    client.Headers[System.Net.HttpRequestHeader.KeepAlive] = "true";
                    //    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
                    //}

                    client.Headers[System.Net.HttpRequestHeader.KeepAlive] = "true";
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;



                    //var GoogleReply = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}&remoteip={2}", PrivateKey, EncodedResponse, WebHelper.UserHost));
                    var GoogleReply = client.UploadString("https://www.google.com/recaptcha/api/siteverify", "POST", string.Format("secret={0}&response={1}&remoteip={2}", PrivateKey, EncodedResponse, WebHelper.UserHost));
                    //captchaResponse.Add("error-net",  string.Format("secret={0}&response={1}&remoteip={2}", PrivateKey, EncodedResponse, WebHelper.UserHost));
                    captchaResponse = jsSerializer.Deserialize <Dictionary <String, Object> >(GoogleReply);
                    XTrace.WriteLine(GoogleReply);
                }
            }
            catch (Exception exc)
            {
                captchaResponse.Add("error-net", exc.Message);
                return(captchaResponse);
            }

            return(captchaResponse);
        }
コード例 #54
0
ファイル: EKMock.cs プロジェクト: xiaocaiyuen/ShuCMS
        /// <summary>
        /// 提交一个字符串到指定路径
        /// </summary>
        /// <param name="url">提交的地址</param>
        /// <param name="type">提交的类型</param>
        /// <param name="message">提交的信息</param>
        /// <returns>提交返回的信息</returns>
        public static string Submit(string url, SubmitType type, string message)
        {
            string result = string.Empty;

            System.Net.WebClient WebClientObj = new System.Net.WebClient();
            try
            {
                result = WebClientObj.UploadString(url, type.ToString(), message);
                WebClientObj.Dispose();
            }
            catch
            {
                //throw ex;
            }
            finally
            {
                WebClientObj.Dispose();
            }

            return(result);
        }
コード例 #55
0
        /// <summary>
        /// 发送
        /// </summary>
        /// <param name="_url"></param>
        /// <param name="data"></param>
        /// <param name="errorDescription"></param>
        /// <returns></returns>
        private static string RequestSend(string _url, string data, ref string errorDescription)
        {
            using (System.Net.WebClient client = new System.Net.WebClient())
            {
                client.Headers["Content-Type"] = "application/json";
                client.Encoding = System.Text.Encoding.UTF8;

                try
                {
                    string strResult = client.UploadString(_url, "post", data);

                    return(strResult);
                }
                catch (Exception ex)
                {
                    errorDescription = ex.Message;

                    return("");
                }
            }
        }
コード例 #56
0
ファイル: Http.cs プロジェクト: secau-perth/Mythic
        public static string Post(string B64Data)
        {
            string    result = null;
            WebClient client = new System.Net.WebClient();

            if (Config.DefaultProxy)
            {
                client.Proxy = WebRequest.DefaultWebProxy;
                client.UseDefaultCredentials = true;
                client.Proxy.Credentials     = CredentialCache.DefaultNetworkCredentials;
            }
            else
            {
                WebProxy proxy = new WebProxy
                {
                    Address = new Uri(Config.ProxyAddress),
                    UseDefaultCredentials = false,
                    Credentials           = new NetworkCredential(Config.ProxyUser, Config.ProxyPassword)
                };
                client.Proxy = proxy;
            }
            client.Headers.Add("User-Agent", Config.UserAgent);
#if NET_4
            if (Config.HostHeader != "")
            {
                client.Headers.Add("Host", Config.HostHeader);
            }
#endif
            Config.Servers = Config.Servers.OrderBy(s => s.count).ToList();
            try
            {
                result = client.UploadString(Config.Servers[0].domain + Config.PostUrl, B64Data);
                return(result);
            }
            catch
            {
                Config.Servers[0].count++;
                return(result);
            }
        }
コード例 #57
0
ファイル: MUser.cs プロジェクト: wudzraina/Travelmart
        /// <summary>
        /// Author:         Josephine Monteza
        /// Date Created:   14/Oct/2015
        /// Description:    Call API to update password in LDAP
        /// </summary>
        /// <returns></returns>
        public static void DeactivateUserInLDAP(string sUsername)
        {
            try
            {
                using (System.Net.WebClient client = new System.Net.WebClient())
                {
                    string sAPI = MUser.GetLDAP();
                    client.Headers.Add("content-type", "application/json");
                    client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";

                    string sAPI_URL   = sAPI + "deactivate";
                    string sAPI_param = "user="******"&company=" + MUser.GetLDAPCompany();

                    string sResult = client.UploadString(sAPI_URL, sAPI_param);
                }
            }
            catch (Exception ex)
            {
                string sMsg = "LDAP Error: " + ex.Message;
            }
        }
コード例 #58
0
ファイル: MUser.cs プロジェクト: wudzraina/Travelmart
        /// <summary>
        /// Author:         Josephine Monteza
        /// Date Created:   14/Oct/2015
        /// Description:    Call API to update password in LDAP
        /// </summary>
        /// <returns></returns>
        public static void ChangePasswordInLDAP(string sUsername, string sNewPassword)
        {
            try
            {
                using (System.Net.WebClient client = new System.Net.WebClient())
                {
                    string sAPI = MUser.GetLDAP();
                    client.Headers.Add("content-type", "application/json");
                    client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";

                    string sAPI_URL   = sAPI + "resetpass";
                    string sAPI_param = "user="******"&pass="******"LDAP Error: " + ex.Message;
            }
        }
コード例 #59
-1
ファイル: UnitTest1.cs プロジェクト: nbIxMaN/HomeWork
 public void AddComets()
 {
     try
     {
         bool s = false;
         var Wc = new WebClient();
         Wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
         var firstdata = "grant_type=password&username="******"TestUserName" + "&password="******"TestPassword361";
         var result1 = Wc.UploadString(SiteUrl + TokenUrl, firstdata);
         JObject o1 = JObject.Parse(result1);
         var token = o1["access_token"].Value<string>();
         Wc.Encoding = Encoding.UTF8;
         Wc.Headers.Add("Content-Type", "application/json");
         string events = Wc.DownloadString(SiteUrl + GetEventsUrl);
         dynamic eventsList = JsonConvert.DeserializeObject(events);
         int Id = eventsList.First.EventId;
         Wc.Headers.Add("Content-Type", "application/json");
         Wc.Headers.Add("Authorization", "Bearer " + token);
         var data = JsonConvert.SerializeObject(new
         {
             Text = "TextComment",
             EntityId = Id.ToString(),
         });
         var result = Wc.UploadString(SiteUrl + AddCommentUrl, data);
         dynamic comment = JsonConvert.DeserializeObject(result);
         int CommentId = comment.CommentId;
         Wc.Headers.Add("Content-Type", "application/json");
         events = Wc.DownloadString(SiteUrl + GetEventsUrl);
         eventsList = JsonConvert.DeserializeObject(events);
         foreach (var i in eventsList)
         {
             if (i.EventId == Id)
             {
                 foreach (var j in i.LastComments)
                 {
                     var a = j.CommentId;
                     var b = j.Text;
                     if ((j.Text == "TextComment") && (j.CommentId == CommentId))
                     {
                         s = true;
                     }
                 }
             }
         }
         if (!s)
         {
             Assert.Fail("Comments not added");
         }
     }
     catch (WebException we)
     {
         Assert.Fail(we.Message);
     }
 }
コード例 #60
-1
        private static string MakeRequest(Settings settings, string baseUrl, string path, string method = "GET", Dictionary<String, String> data = null)
        {
            string url = baseUrl + path;
            //create an instance of OAuthRequest with the appropriate properties
            OAuthRequest client = new OAuthRequest
            {
                Method = method,
                Type = OAuthRequestType.RequestToken,
                SignatureMethod = OAuthSignatureMethod.HmacSha1,
                ConsumerKey = settings.consumerKey,
                ConsumerSecret = GetSha1(settings.consumerSecret, settings.salt),
                RequestUrl = url
            };

            string auth = client.GetAuthorizationHeader();
            WebClient c = new WebClient();
            c.Headers.Add("Authorization", auth);
            c.BaseAddress = baseUrl;
            if (method == "GET")
            {
                return c.DownloadString(path);
            }
            else
            {
                c.Headers[HttpRequestHeader.ContentType] = "application/json";
                return c.UploadString(path, JsonConvert.SerializeObject(data));
            }
        }