当前位置: 首页>>代码示例>>C#>>正文


C# WebClient.UploadString方法代码示例

本文整理汇总了C#中System.Net.WebClient.UploadString方法的典型用法代码示例。如果您正苦于以下问题:C# WebClient.UploadString方法的具体用法?C# WebClient.UploadString怎么用?C# WebClient.UploadString使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Net.WebClient的用法示例。


在下文中一共展示了WebClient.UploadString方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: AddNewGameHistory

        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;
        }
开发者ID:NBitionDevelopment,项目名称:ToSavour-Service,代码行数:27,代码来源:ServiceOracle.cs

示例2: Main

        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();
                }
            }
        }
开发者ID:tian1ll1,项目名称:WPF_Examples,代码行数:52,代码来源:Program.cs

示例3: GetWatchedEpisodes

        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;
            }
        }
开发者ID:david-ju,项目名称:Watched,代码行数:50,代码来源:KodiConnector.cs

示例4: OnMethod

        /// <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);
            }
        }
开发者ID:sat1582,项目名称:CODEFramework,代码行数:55,代码来源:RestProxyHandler.cs

示例5: Stubs_should_be_unique_within_context

        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));
        }
开发者ID:nicklbailey,项目名称:HttpMock,代码行数:15,代码来源:MultipleTestsUsingTheSameStubServer.cs

示例6: test

        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);


        }
开发者ID:s7loves,项目名称:mypowerscgl,代码行数:31,代码来源:Program.cs

示例7: SendToMirror

 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"];
 }
开发者ID:henninga,项目名称:fubumvc,代码行数:7,代码来源:ConnegFixture.cs

示例8: Main

        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();
            }
        }
开发者ID:windrobin,项目名称:kumpro,代码行数:35,代码来源:Program.cs

示例9: CallAPI

        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;
            }
        }
开发者ID:bjarkimg,项目名称:MPExtended,代码行数:25,代码来源:TraktAPI.cs

示例10: GetRecordInfo

       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;
       }
开发者ID:ufjl0683,项目名称:wirelessBrocast,代码行数:33,代码来源:Recoder.cs

示例11: Execute

        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;
        }
开发者ID:frankmeola,项目名称:BuildExtensions,代码行数:32,代码来源:Publish.cs

示例12: OnSendRequest

        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();
        }
开发者ID:kow,项目名称:Aurora-Sim,代码行数:28,代码来源:HttpServerLoadTests.cs

示例13: GetStoreProducts

        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);
        }
开发者ID:Badaro,项目名称:MtgPriceOptimizer,代码行数:60,代码来源:MagicDomain.cs

示例14: buttonIdentify_Click

        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=" + Uri.EscapeDataString(textPassword.Text));
              } catch { }

              if (!result.Contains("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]);
        }
开发者ID:jamesmanning,项目名称:Clipupload,代码行数:28,代码来源:FormSettings.cs

示例15: Login

 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);
 }
开发者ID:hudl,项目名称:black-mesa,代码行数:27,代码来源:AuthenticationController.cs


注:本文中的System.Net.WebClient.UploadString方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。