本文整理汇总了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;
}
示例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();
}
}
}
示例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;
}
}
示例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);
}
}
示例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));
}
示例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);
}
示例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"];
}
示例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();
}
}
示例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;
}
}
示例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;
}
示例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;
}
示例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();
}
示例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("Æ", "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);
}
示例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]);
}
示例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);
}