本文整理汇总了C#中WebClient.UploadData方法的典型用法代码示例。如果您正苦于以下问题:C# WebClient.UploadData方法的具体用法?C# WebClient.UploadData怎么用?C# WebClient.UploadData使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类WebClient
的用法示例。
在下文中一共展示了WebClient.UploadData方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetAuthorizationUrl
/// <summary>
/// Retrieve the URL that the client should redirect the user to to perform the OAuth authorization
/// </summary>
/// <param name="provider"></param>
/// <returns></returns>
protected override string GetAuthorizationUrl(String callbackUrl)
{
OAuthBase auth = new OAuthBase();
String requestUrl = provider.Host + provider.RequestTokenUrl;
Uri url = new Uri(requestUrl);
String requestParams = "";
String signature = auth.GenerateSignature(url, provider.ClientId, provider.Secret, null, null, provider.RequestTokenMethod ?? "POST",
auth.GenerateTimeStamp(), auth.GenerateTimeStamp() + auth.GenerateNonce(), out requestUrl, out requestParams,
new OAuthBase.QueryParameter(OAuthBase.OAuthCallbackKey, auth.UrlEncode(callbackUrl)));
requestParams += "&oauth_signature=" + HttpUtility.UrlEncode(signature);
WebClient webClient = new WebClient();
byte[] response;
if (provider.RequestTokenMethod == "POST" || provider.RequestTokenMethod == null)
{
response = webClient.UploadData(url, Encoding.ASCII.GetBytes(requestParams));
}
else
{
response = webClient.DownloadData(url + "?" + requestParams);
}
Match m = Regex.Match(Encoding.ASCII.GetString(response), "oauth_token=(.*?)&oauth_token_secret=(.*?)&oauth_callback_confirmed=true");
String requestToken = m.Groups[1].Value;
String requestTokenSecret = m.Groups[2].Value;
// we need a way to save the request token & secret, so that we can use it to get the access token later (when they enter the pin)
// just stick it in the session for now
HttpContext.Current.Session[OAUTH1_REQUEST_TOKEN_SESSIONKEY] = requestToken;
HttpContext.Current.Session[OAUTH1_REQUEST_TOKEN_SECRET_SESSIONKEY] = requestTokenSecret;
return provider.Host + provider.UserApprovalUrl + "?oauth_token=" + HttpUtility.UrlEncode(requestToken);
}
示例2: UpFile
/// <summary>
/// WebClient.UploadFile()
/// </summary>
public static void UpFile()
{
WebClient client = new WebClient();
client.UploadFile("http://www.baidu.com", "C:/Users/yk199/Desktop/GodWay1/Web/Log/newfile.txt");
byte[] image = new byte[2];
client.UploadData("http://www.baidu.com",image);
}
示例3: Push
public string Push(string user_id, string title, string description, string msg_keys)
{
DateTime utcNow = DateTime.UtcNow;
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0);
uint timestamp = (uint)(utcNow - epoch).TotalSeconds;
uint expires = (uint)(utcNow.AddDays(1) - epoch).TotalSeconds; //一天后过期
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("method", method);
dic.Add("apikey", apikey);
dic.Add("timestamp", timestamp.ToString());
dic.Add("push_type", "1"); //单播
dic.Add("device_type", "3"); //Andriod设备
dic.Add("user_id", user_id);
dic.Add("message_type", "0"); //消息
dic.Add("messages", description);
dic.Add("msg_keys", msg_keys); //消息标识 相同消息标识的消息会自动覆盖。只支持android。
dic.Add("sign", StructSign("POST", url, dic, secret_key));
StringBuilder sb = new StringBuilder();
foreach (var d in dic)
{
sb.Append(d.Key + "=" + d.Value + "&");
}
sb.Remove(sb.Length - 1, 1);
byte[] data = Encoding.UTF8.GetBytes(sb.ToString());
WebClient webClient = new WebClient();
try
{
webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");//采取POST方式必须加的header,如果改为GET方式的话就去掉这句话即可
byte[] response = webClient.UploadData(url, "POST", data);
return Encoding.UTF8.GetString(response);
}
catch (WebException ex)
{
Stream stream = ex.Response.GetResponseStream();
byte[] bs = new byte[256];
int i = 0;
int b;
while ((b = stream.ReadByte()) > 0)
{
bs[i++] = (byte)b;
}
stream.Close();
return Encoding.UTF8.GetString(bs, 0, i);
}
}
示例4: GetAccessToken
private void GetAccessToken(string requestToken, string requestTokenSecret, string verifier, out string accessToken, out string accessTokenSecret, out string username)
{
Uri url = new Uri(provider.Host + provider.AccessTokenUrl);
OAuthBase auth = new OAuthBase();
String requestUrl, requestParams;
String signature = auth.GenerateSignature(url, provider.ClientId, provider.Secret, requestToken, requestTokenSecret, provider.RequestTokenMethod ?? "POST",
auth.GenerateTimeStamp(), auth.GenerateTimeStamp() + auth.GenerateNonce(), out requestUrl, out requestParams,
new OAuthBase.QueryParameter("oauth_verifier", auth.UrlEncode(verifier)));
WebClient webClient = new WebClient();
byte[] response = webClient.UploadData(url, Encoding.ASCII.GetBytes(requestParams + "&oauth_signature=" + HttpUtility.UrlEncode(signature)));
String[] tokenParts = Encoding.ASCII.GetString(response).Split('&');
if (tokenParts.Length < 2)
{
throw new Exception("Unexpected response to access token request: " + Encoding.ASCII.GetString(response));
}
accessToken = null;
accessTokenSecret = null;
username = null;
foreach (String tokenPart in tokenParts)
{
String[] pieces = tokenPart.Split('=');
if (pieces.Length != 2)
{
throw new Exception("Unable to parse HTTP response: " + tokenPart); // should not happen
}
switch (pieces[0])
{
case OAuthBase.OAuthTokenKey:
accessToken = pieces[1];
break;
case OAuthBase.OAuthTokenSecretKey:
accessTokenSecret = pieces[1];
break;
case "screen_name": case "user_name":
// Twitter provides the user name back with this call, though it's not part of the standard.
// we'll capture it if it's provided and leave it null if not (it's not really required for anything anyway)
username = pieces[1];
break;
default:
// ignore other values
break;
}
}
}
示例5: GetWebClientData
//---------------------------------------------------------
private string GetWebClientData(string targetUrl)
{
//Cmn.Log.WriteToFile("targetUrl", targetUrl);
string _retVal = "";
WebClient _webClient = new WebClient();
//增加SessionID,为了解决当前用户登录问题
// Cmn.Session.SetUserID("kdkkk"); //随便设置一个session 否则SessionID会变
Cmn.Session.Set("cmn_ItfProxy_tmp","test");
targetUrl = Cmn.Func.AddParamToUrl(targetUrl, "CurSessionID=" + Session.SessionID);
Cmn.Log.WriteToFile("targetUrl", targetUrl);
if (Request.Form.Count > 0) { //post方式
string _postString = "";
for (int _i = 0; _i < Request.Form.Count; _i++) {
if (_postString != "") { _postString += "&"; }
_postString += Request.Form.Keys[_i] + "=" + System.Web.HttpUtility.UrlEncode(Request.Form[_i].ToString(), Encoding.UTF8);
}
byte[] _postData = Encoding.GetEncoding("utf-8").GetBytes(_postString);
_webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
byte[] _responseData = _webClient.UploadData(targetUrl, "POST", _postData);//得到返回字符流
_retVal = Encoding.GetEncoding("utf-8").GetString(_responseData);//解码
}
else {
Stream _stream = _webClient.OpenRead(targetUrl);
StreamReader _rd = new StreamReader(_stream, Encoding.GetEncoding("utf-8"));
_retVal = _rd.ReadToEnd();
_stream.Close();
}
return _retVal;
}
示例6: UploadData_InvalidArguments_ThrowExceptions
public static void UploadData_InvalidArguments_ThrowExceptions()
{
var wc = new WebClient();
Assert.Throws<ArgumentNullException>("address", () => { wc.UploadData((string)null, null); });
Assert.Throws<ArgumentNullException>("address", () => { wc.UploadData((string)null, null, null); });
Assert.Throws<ArgumentNullException>("address", () => { wc.UploadData((Uri)null, null); });
Assert.Throws<ArgumentNullException>("address", () => { wc.UploadData((Uri)null, null, null); });
Assert.Throws<ArgumentNullException>("address", () => { wc.UploadDataAsync((Uri)null, null); });
Assert.Throws<ArgumentNullException>("address", () => { wc.UploadDataAsync((Uri)null, null, null); });
Assert.Throws<ArgumentNullException>("address", () => { wc.UploadDataAsync((Uri)null, null, null, null); });
Assert.Throws<ArgumentNullException>("address", () => { wc.UploadDataTaskAsync((string)null, null); });
Assert.Throws<ArgumentNullException>("address", () => { wc.UploadDataTaskAsync((string)null, null, null); });
Assert.Throws<ArgumentNullException>("address", () => { wc.UploadDataTaskAsync((Uri)null, null); });
Assert.Throws<ArgumentNullException>("address", () => { wc.UploadDataTaskAsync((Uri)null, null, null); });
Assert.Throws<ArgumentNullException>("data", () => { wc.UploadData("http://localhost", null); });
Assert.Throws<ArgumentNullException>("data", () => { wc.UploadData("http://localhost", null, null); });
Assert.Throws<ArgumentNullException>("data", () => { wc.UploadData(new Uri("http://localhost"), null); });
Assert.Throws<ArgumentNullException>("data", () => { wc.UploadData(new Uri("http://localhost"), null, null); });
Assert.Throws<ArgumentNullException>("data", () => { wc.UploadDataAsync(new Uri("http://localhost"), null); });
Assert.Throws<ArgumentNullException>("data", () => { wc.UploadDataAsync(new Uri("http://localhost"), null, null); });
Assert.Throws<ArgumentNullException>("data", () => { wc.UploadDataAsync(new Uri("http://localhost"), null, null, null); });
Assert.Throws<ArgumentNullException>("data", () => { wc.UploadDataTaskAsync("http://localhost", null); });
Assert.Throws<ArgumentNullException>("data", () => { wc.UploadDataTaskAsync("http://localhost", null, null); });
Assert.Throws<ArgumentNullException>("data", () => { wc.UploadDataTaskAsync(new Uri("http://localhost"), null); });
Assert.Throws<ArgumentNullException>("data", () => { wc.UploadDataTaskAsync(new Uri("http://localhost"), null, null); });
}
示例7: UploadDataAsync
protected override Task<byte[]> UploadDataAsync(WebClient wc, string address, byte[] data) => Task.Run(() => wc.UploadData(address, data));
示例8: ConcurrentOperations_Throw
public static async Task ConcurrentOperations_Throw()
{
await LoopbackServer.CreateServerAsync((server, url) =>
{
var wc = new WebClient();
Task ignored = wc.DownloadDataTaskAsync(url); // won't complete
Assert.Throws<NotSupportedException>(() => { wc.DownloadData(url); });
Assert.Throws<NotSupportedException>(() => { wc.DownloadDataAsync(url); });
Assert.Throws<NotSupportedException>(() => { wc.DownloadDataTaskAsync(url); });
Assert.Throws<NotSupportedException>(() => { wc.DownloadString(url); });
Assert.Throws<NotSupportedException>(() => { wc.DownloadStringAsync(url); });
Assert.Throws<NotSupportedException>(() => { wc.DownloadStringTaskAsync(url); });
Assert.Throws<NotSupportedException>(() => { wc.DownloadFile(url, "path"); });
Assert.Throws<NotSupportedException>(() => { wc.DownloadFileAsync(url, "path"); });
Assert.Throws<NotSupportedException>(() => { wc.DownloadFileTaskAsync(url, "path"); });
Assert.Throws<NotSupportedException>(() => { wc.UploadData(url, new byte[42]); });
Assert.Throws<NotSupportedException>(() => { wc.UploadDataAsync(url, new byte[42]); });
Assert.Throws<NotSupportedException>(() => { wc.UploadDataTaskAsync(url, new byte[42]); });
Assert.Throws<NotSupportedException>(() => { wc.UploadString(url, "42"); });
Assert.Throws<NotSupportedException>(() => { wc.UploadStringAsync(url, "42"); });
Assert.Throws<NotSupportedException>(() => { wc.UploadStringTaskAsync(url, "42"); });
Assert.Throws<NotSupportedException>(() => { wc.UploadFile(url, "path"); });
Assert.Throws<NotSupportedException>(() => { wc.UploadFileAsync(url, "path"); });
Assert.Throws<NotSupportedException>(() => { wc.UploadFileTaskAsync(url, "path"); });
Assert.Throws<NotSupportedException>(() => { wc.UploadValues(url, new NameValueCollection()); });
Assert.Throws<NotSupportedException>(() => { wc.UploadValuesAsync(url, new NameValueCollection()); });
Assert.Throws<NotSupportedException>(() => { wc.UploadValuesTaskAsync(url, new NameValueCollection()); });
return Task.CompletedTask;
});
}
示例9: createAndSendFileOnFtp
IEnumerator createAndSendFileOnFtp(string id)
{
ExtraEvent.firePleaseWait(true);
t = Time.time;
debugString = "-started:"+t;
yield return new WaitForSeconds(1);
byte[] img = m_sendPic.EncodeToPNG();
string fileName = Path.GetRandomFileName();
fileName = fileName.Replace(".","");
// Debug.Log("Unique fName>" + fileName+"<");
// ALTERNATE VERSION VV DOESN'T WORK MOUAHAHAH ^^
// FileStream fs = File.Open(Application.persistentDataPath+"/test.png",FileMode.Open);
// fs.Flush();
// fs.Write(img,0,img.Length);
// fs.Close();
//
// string filename = "Bitcherland.png";
// FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create("ftp://www.oneshot3d.com/ExtraTest/"+filename);
// ftpRequest.Method = WebRequestMethods.Ftp.UploadFileWithUniqueName;
// ftpRequest.Credentials = new NetworkCredential("sys_pointcub","gx8FztlI7kpM");
//
//// StreamReader sr = new StreamReader(Application.persistentDataPath+"/test.png");
//// byte[] fileContent = Encoding.UTF8.GetBytes(sr.ReadToEnd());
//// sr.Close();
////
//// ftpRequest.ContentLength = fileContent.Length;
//
// Stream requestStream = ftpRequest.GetRequestStream();
// requestStream.Write(img,0,img.Length);
// requestStream.Close();
//
// FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse();
//
//// Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
// Debug.Log("UploadFile complete, >"+response.StatusDescription);
// response.Close();
debugString += "-startwc:"+Time.time;
WebClient wc = new WebClient();
wc.Credentials = new NetworkCredential("sys_pointcub","gx8FztlI7kpM"); //local
wc.UploadData("ftp://www.pointcube.com/extrabat/img/"+fileName+".png",img);
wc.Dispose();
debugString += "-endwc:"+Time.time;
Debug.Log("COROUTINE UPLOAD FINNISHED");
yield return new WaitForSeconds(1);
StartCoroutine(fileOnServer(id,fileName));
yield return null;
}
示例10: GetAccessToken
/// <summary>
/// Retrieve access or refresh token
/// </summary>
/// <param name="accessCode"></param>
/// <param name="url"></param>
/// <param name="urlData"></param>
/// <param name="callbackUrl">Original callback URL (used for verification by some provider)</param>
/// <returns></returns>
private TokenResponse GetAccessToken(string accessCode, String url, String urlData, String callbackUrl)
{
urlData = urlData.Replace("{REDIRECT_URI}", HttpUtility.UrlEncode(callbackUrl));
urlData = urlData.Replace("{TOKEN}", HttpUtility.UrlEncode(accessCode));
urlData = urlData.Replace("{CLIENTID}", provider.ClientId);
urlData = urlData.Replace("{CLIENTSECRET}", provider.Secret);
// I don't think we need that one - if the provider requires refresh token, we'll be using the refresh URL instead
//if (provider.RequiresRefreshToken.GetValueOrDefault())
// urlData += "&access_type=offline";
try
{
var client = new WebClient();
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
// TODO: support for "GET" method
byte[] response = client.UploadData(url, Encoding.ASCII.GetBytes(urlData));
TokenResponse tResponse = JsonConvert.DeserializeObject<TokenResponse>(Encoding.ASCII.GetString(response));
if (tResponse.error != null)
throw new Exception(tResponse.error);
return tResponse;
}
catch (Exception ex)
{
if (ex is WebException)
{
using (var sr = new StreamReader(((WebException)ex).Response.GetResponseStream()))
{
String responseString = sr.ReadToEnd();
if (!String.IsNullOrEmpty(responseString))
{
_log.Warn("Error Response from OAuth provider: " + responseString);
}
}
}
throw new ValidationException(String.Format("Unable to retrieve authorization token: {0}", ex.Message));
}
}
示例11: SendMessage
public static string SendMessage(string Url, string strMessage)
{
string strResponse;
// 初始化WebClient
WebClient webClient = new WebClient();
webClient.Headers.Add("Accept", "*/*");
webClient.Headers.Add("Accept-Language", "zh-cn");
webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
try
{
byte[] responseData = webClient.UploadData(Url, "POST", Encoding.GetEncoding("UTF-8").GetBytes(strMessage));
string srcString = Encoding.GetEncoding("UTF-8").GetString(responseData);
strResponse = srcString;
}
catch
{
return "-1";
}
return strResponse;
}
示例12: PushImage
static void PushImage(string file)
{
Console.WriteLine (file);
using (WebClient wc = new WebClient ()) {
wc.Headers.Add ("X-Apple-AssetKey", "F92F9B91-954E-4D63-BB9A-EEC771ADE6E8");
wc.Headers.Add ("User-Agent", "AirPlay/160.4 (Photos)");
wc.Headers.Add ("X-Apple-Session-ID", "1bd6ceeb-fffd-456c-a09c-996053a7a08c");
var data = File.ReadAllBytes (file);
// FIXME: change address to match your device
wc.UploadData ("http://your.apple.tv:7000/photo", "PUT", data);
}
}
示例13: getHtml
/// <summary>
/// Private accessor for all GET and POST requests.
/// </summary>
/// <param name="url">Web url to be accessed.</param>
/// <param name="post">Place POST request information here. If a GET request, use null. </param>
/// <param name="attempts"># of attemtps before sending back an empty string.</param>
/// <returns>Page HTML if access was successful, otherwise will return a blank string. </returns>
private String getHtml(String url, String post, int attempts)
{
WebClient webClient = new WebClient();
UTF8Encoding utfObj = new UTF8Encoding();
byte[] reqHTML;
while (attempts > 0)// Will keep trying to access until attempts reach zero.
{
try
{
if (post != null) //If post is null, then no post request is required.
reqHTML = webClient.UploadData(url, "POST", System.Text.Encoding.ASCII.GetBytes(post));
else
reqHTML = webClient.DownloadData(url);
String input = utfObj.GetString(reqHTML);
return input;
}
catch (WebException e)
{
errorLog.WriteMessage("Could not contact to " + url + " - " + e.Message);
Thread.Sleep(2000);
}
catch (ArgumentNullException e)
{
errorLog.WriteMessage("Could not retrieve data from " + url + " - " + e.Message);
Thread.Sleep(2000);
}
attempts--;
}
return "";
}