本文整理汇总了C#中System.Net.WebClient.UploadData方法的典型用法代码示例。如果您正苦于以下问题:C# WebClient.UploadData方法的具体用法?C# WebClient.UploadData怎么用?C# WebClient.UploadData使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.WebClient
的用法示例。
在下文中一共展示了WebClient.UploadData方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ExecutePost
public String ExecutePost()
{
Random rd = new Random();
int rd_i = rd.Next();
String nonce = Convert.ToString(rd_i);
String timestamp = Convert.ToString(ConvertDateTimeInt(DateTime.Now));
String signature = GetHash(this.appSecret + nonce + timestamp);
//ServicePointManager.ServerCertificateValidationCallback += ValidateRemoteCertificate;
//ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
WebClient myWebClient = new WebClient();
myWebClient.Headers.Add("App-Key", this.appkey);
myWebClient.Headers.Add("Nonce", nonce);
myWebClient.Headers.Add("Timestamp", timestamp);
myWebClient.Headers.Add("Signature", signature);
myWebClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
byte[] byteArray = Encoding.UTF8.GetBytes(this.postStr);
byte[] responseArray = myWebClient.UploadData(this.methodUrl, "POST", byteArray);
return Encoding.UTF8.GetString(responseArray);
}
示例2: CreateUser
public static string CreateUser(string user_token, string firstname, string lastname,string password, string username)
{
WebClient restClient = new WebClient();
restClient.Headers.Add("Content-Type", Global.ASSITments_ContentType);
restClient.Headers.Add("assistments-auth", Global.ASSITments_Auth_WOBehalf);
string createUserURL = String.Format("{0}/user", Global.ASSITmentsBaseAPI);
string postData = "{" + "\"" + "userType" + "\"" + ":" + "\"" + "proxy" + "\"" + "," +
"\"" + "username" + "\"" + ":" + "\"" + username + "\"" + "," +
"\"" + "password" + "\"" + ":" + "\"" + password + "\"" + "," +
"\"" + "email" + "\"" + ":" + "\"" + "4" + firstname + lastname + "@junk.com" + "\"" + "," +
"\"" + "firstName" + "\"" + ":" + "\"" + firstname + "\"" + "," +
"\"" + "lastName" + "\"" + ":" + "\"" + lastname + "\"" + "," +
"\"" + "displayName" + "\"" + ":" + "\"" + "4" + firstname + " " + lastname + "\"" + "," +
"\"" + "timeZone" + "\"" + ":" + "\"" + "GMT-4" + "\"" + "," +
"\"" + "registrationCode" + "\"" + ":" + "\"" + "HIEN-API" + "\"" + "}";
byte[] byteArray = Encoding.ASCII.GetBytes(postData);
byte[] byteResult = restClient.UploadData(createUserURL, "POST", byteArray);
string retStr = Encoding.ASCII.GetString(byteResult);
JObject response = JObject.Parse(retStr);
string student_ref = response["user"].ToString();
return student_ref;
}
示例3: AcceptedRequestOffersBody
public void AcceptedRequestOffersBody()
{
Server.EndPoints.Add(ListenPort);
Scheduler.WaitFor(Server.StartListening());
var dataToUpload = new byte[1024 * 1024];
for (var i = 0; i < dataToUpload.Length; i++)
dataToUpload[i] = (byte)(i % 256);
using (var wc = new WebClient()) {
var fPost = Future.RunInThread(
() => {
var result = wc.UploadData(ServerUri, dataToUpload);
Console.WriteLine("Upload complete");
return result;
}
);
var request = Scheduler.WaitFor(Server.AcceptRequest(), 3);
Console.WriteLine(request);
Assert.AreEqual("POST", request.Line.Method);
Assert.AreEqual("localhost", request.Line.Uri.Host);
Assert.AreEqual("/", request.Line.Uri.AbsolutePath);
var requestBody = Scheduler.WaitFor(request.Body.Bytes);
Assert.AreEqual(dataToUpload.Length, requestBody.Length);
Assert.AreEqual(dataToUpload, requestBody);
request.Dispose();
Scheduler.WaitFor(fPost, WebClientTimeout);
}
}
示例4: UploadBytesAsync
private Task<string> UploadBytesAsync(string method, IProgress<string> progress)
{
return Task.Run(() =>
{
using (var client = new WebClient())
{
var address = restClient.PrepareUri();
restClient.SetHeaders(client);
client.TraceRequest(address, method, progress);
var watch = new Stopwatch();
watch.Start();
client.UploadData(address, method, content);
watch.Stop();
client.TraceResponse(address,
method,
string.Format(CultureInfo.InvariantCulture,
"Completed in {0} seconds",
watch.Elapsed.TotalSeconds),
progress);
}
return "Done";
});
}
示例5: enrollStuentInClass
public static bool enrollStuentInClass(string user_ref, string class_ref, string onBehalfOf)
{
WebClient restClient = new WebClient();
restClient.Headers.Add("Content-Type", Global.ASSITments_ContentType);
String AuthOnBehalf = "partner=" + "\"" + "Hien-Ref" + "\",onBehalfOf=" + "\"" + onBehalfOf + "\"";
restClient.Headers.Add("assistments-auth", AuthOnBehalf);
string enrollStudentClass = String.Format("{0}/class_membership", Global.ASSITmentsBaseAPI);
string postData = "{" + "\"" + "user" + "\"" + ":" + "\"" + user_ref + "\"" + "," +
"\"" + "class" + "\"" + ":" + "\"" + class_ref + "\"" + "}";
byte[] byteResult = new byte[]{};
byte[] byteArray = Encoding.ASCII.GetBytes(postData);
try
{
byteResult = restClient.UploadData(enrollStudentClass, "POST", byteArray);
}
catch (Exception e)
{
return false;
}
string retStr = Encoding.ASCII.GetString(byteResult);
return true;
}
示例6: Translate
public override string Translate(string text, ref string from)
{
string transText = "";
string transURL = "http://www.freetranslation.com/gw-mt-proxy-service-web/mt-translation";
try
{
using (WebClient client = new WebClient())
{
NameValueCollection headers = new NameValueCollection()
{
{ "Content-Type", "application/json; charset=UTF-8" },
{ "Tracking", "applicationKey=dlWbNAC2iLJWujbcIHiNMQ%3D%3D applicationInstance=freetranslation" } // Public translarion service
};
client.Headers.Add(headers);
JObject postData = new JObject();
postData["text"] = HttpUtility.UrlEncode(text);
postData["from"] = from;
postData["to"] = "eng";
byte[] b_transResp = client.UploadData(transURL, Encoding.UTF8.GetBytes(postData.ToString()));
string transResp = Encoding.UTF8.GetString(b_transResp);
JObject trObject = JObject.Parse(transResp);
transText = trObject["translation"].ToString().TrimStart();
}
}
catch (Exception e) { transText = text; from = "ERROR"; }
return transText.Length > 0 ? transText : text;
}
示例7: CreateNew
public static string CreateNew(string courseName, string courseNumber, string sectionNumber, string onBehalf)
{
string retStr = "";
WebClient restClient = new WebClient();
restClient.Headers.Add("Content-Type", Global.ASSITments_ContentType);
String AuthOnBehalf = "partner=" + "\"" + "Hien-Ref" + "\",onBehalfOf=" + "\"" + onBehalf + "\"";
restClient.Headers.Add("assistments-auth", AuthOnBehalf);
string createClassURL = String.Format("{0}/student_class", Global.ASSITmentsBaseAPI);
//string postData = "{" + "\"" + "courseName" + "\"" + ":" + "\"" + courseName + "\"" + "," +
// "\"" + "courseNumber" + "\"" + ":" + "\"" + courseNumber + "\"" + "," +
// "\"" + "sectionNumber" + "\"" + ":" + "\"" + sectionNumber + "\"" + "}";
string postData = "{" + "\"" + "courseName" + "\"" + ":" + "\"" + courseName + "\"" + "}";
byte[] byteArray = Encoding.ASCII.GetBytes(postData);
byte[] byteResult = restClient.UploadData(createClassURL, "POST", byteArray);
retStr = Encoding.ASCII.GetString(byteResult);
JObject response = JObject.Parse(retStr);
string classRef = response["class"].ToString();
return classRef;
}
示例8: ASSITments_CreateAssignment
protected void ASSITments_CreateAssignment(object sender, EventArgs e)
{
WebClient restClient = new WebClient();
restClient.Headers.Add("Content-Type", Global.ASSITments_ContentType);
// restClient.Headers.Add("assistments-auth", "partner=" + "\"" + "Hien-Ref" + "\",onBehalfOf=" + Session["OnBehalfOf"]); //Session["OnBehalfOf"]: linkUser.aspx
restClient.Headers.Add("assistments-auth", Global.ASSITments_Auth_Behalf);
if (Global.OnBehalfOf == "")
{
this.lblASSIT_AssignmentError.Visible = true;
return;
}
string createAssignmentURL = String.Format("{0}/assignment",Global.ASSITmentsBaseAPI);
string postData = "{" + "\"" + "problemSet" + "\"" + ":" + "\"" + Global.problemSetId + "\"" + "," +
"\"" + "class" + "\"" + ":" + "\"" + Global.classRef + "\"" + "," +
"\"" + "scope" + "\"" + ":" + "\"" + Global.classRef + "\"" + "}";
byte[] byteArray = Encoding.ASCII.GetBytes(postData);
byte[] byteResult = restClient.UploadData(createAssignmentURL, "POST", byteArray);
string retStr = Encoding.ASCII.GetString(byteResult);
JObject response = JObject.Parse(retStr);
string assignment_ref = response["assignment"].ToString();
Global.assignmentRef = assignment_ref;
this.lblASSIT_AssignmentOK.Visible = true;
}
示例9: GetUUID
/// <summary>
/// Retrieve the UUID given a username
/// This one is no longer used during auth since the new method get the UUID
/// </summary>
public static Guid GetUUID(string username)
{
using (WebClient client = new WebClient())
{
/*
'header' => "Content-type: application/json\r\n",
'method' => 'POST',
'content' => '{"name":"'.$username.'","agent":"minecraft"}',
context = stream_context_create(options);
result = file_get_contents(url, false, $context);
return res;
*/
var request = new Request();
request.name = username;
byte[] req = Json.Serialize(request);
// Download data.
byte[] resp = client.UploadData(url, req);
var response = Json.Deserialize<Response>(resp);
if(response.profiles.Count == 0)
throw new InvalidOperationException("Bad response: " + Encoding.UTF8.GetString(resp));
Guid id = response.profiles[0].id;
if (id == Guid.Empty)
throw new InvalidOperationException("Bad response: " + Encoding.UTF8.GetString(resp));
return id;
}
}
示例10: RunAsync
public void RunAsync()
{
var ctx = System.Threading.SynchronizationContext.Current;
System.Threading.ThreadPool.QueueUserWorkItem(state => {
var client = new WebClient();
var rand = new Random();
var data = new byte[DataSize];
rand.NextBytes(data);
var results = new BandwidthCheckResult[Tries];
for (var i=0; i<Tries; i++) {
try {
var stopwatch = new System.Diagnostics.Stopwatch();
stopwatch.Start();
var response_body = client.UploadData(Target, data);
stopwatch.Stop();
results[i].ElapsedTime = stopwatch.Elapsed;
results[i].Succeeded = true;
}
catch (WebException) {
results[i].Succeeded = false;
}
}
if (BandwidthCheckCompleted!=null) {
var success = results.Count(r => r.Succeeded)>0;
var average_seconds = results.Average(r => r.ElapsedTime.TotalSeconds);
ctx.Post(s => {
BandwidthCheckCompleted(
this,
new BandwidthCheckCompletedEventArgs(success, DataSize, TimeSpan.FromSeconds(average_seconds)));
}, null);
}
});
}
示例11: UploadExcelFromSqlToDropBox
public void UploadExcelFromSqlToDropBox(string savedQuery, string sqlscript, string targetpath, string filename)
{
using (var db2 = NewDataContext())
{
var accesstoken = db2.Setting("DropBoxAccessToken", ConfigurationManager.AppSettings["DropBoxAccessToken"]);
var script = db2.Content(sqlscript, "");
if (!script.HasValue())
throw new Exception("no sql script found");
var p = new DynamicParameters();
foreach (var kv in dictionary)
p.Add("@" + kv.Key, kv.Value);
if (script.Contains("@qtagid"))
{
int? qtagid = null;
if (savedQuery.HasValue())
{
var q = db2.PeopleQuery2(savedQuery);
var tag = db2.PopulateSpecialTag(q, DbUtil.TagTypeId_Query);
qtagid = tag.Id;
}
p.Add("@qtagid", qtagid);
}
var bytes = db2.Connection.ExecuteReader(script, p).ToExcelBytes(filename);
var wc = new WebClient();
wc.Headers.Add($"Authorization: Bearer {accesstoken}");
wc.Headers.Add("Content-Type: application/octet-stream");
wc.Headers.Add([email protected]"Dropbox-API-Arg: {{""path"":""{targetpath}/{filename}"",""mode"":""overwrite""}}");
wc.UploadData("https://content.dropboxapi.com/2-beta-2/files/upload", bytes);
}
}
示例12: DeleteChannel
public static void DeleteChannel(String token)
{
try {
String json = "{\"token\":\"" + token + "\"}";
var client = new System.Net.WebClient();
client.Headers.Add("Content-Type", "application/json");
var resp = client.UploadData(Const.LiveDeleteUrl, "POST",
System.Text.Encoding.UTF8.GetBytes(json));
var respStr = System.Text.Encoding.UTF8.GetString(resp);
var result = SimpleJsonParser.Parse(respStr); ;
int status = 99;
if (result.ContainsKey("status")) {
status = int.Parse(result["status"]);
if (status == 0) {
return;
}
}
throw new CloudException(status, "");
} catch (WebException e) {
throw new CloudException(99, e.ToString());
}
}
示例13: of_SendPost
public static string of_SendPost(string Url, string Params)
{
if (GYstring.of_LeftStr(Url, 7).ToLower() != "http://")
{
Url = "http://" + Url;
}
//初始化WebClient
System.Net.WebClient webClient = new System.Net.WebClient();
webClient.Headers.Add("Accept", "*/*");
webClient.Headers.Add("Accept-Language", "zh-cn");
webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
webClient.Headers.Add(HttpRequestHeader.KeepAlive, "FALSE");
//将字符串转换成字节数组
string srcString;
byte[] postData = Encoding.GetEncoding("GB2312").GetBytes(Params);
try
{
byte[] responseData = webClient.UploadData(Url, "POST", postData);
srcString = Encoding.GetEncoding("GB2312").GetString(responseData);
srcString = GYstring.of_trim(srcString);
}
catch (Exception Exce)
{
return Exce.ToString();
}
return srcString;
}
示例14: GetFirstLevelDepartmentIdByDepartment
public string[] GetFirstLevelDepartmentIdByDepartment(int departmentId)
{
string postString = string.Join("&", "url=http://service.dianping.com/ba/base/organizationalstructure/OrganizationService_1.0.0"
, "method=getDepartmentHierarchy"
, "parameterTypes=int"
, "parameters=" + departmentId.ToString());
byte[] postData = Encoding.UTF8.GetBytes(postString);
List<Department> departmentList = new List<Department>();
using (WebClient client = new WebClient())
{
client.Headers.Add("serialize", 7.ToString());
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
byte[] responseData = client.UploadData(ORGANIZATIONAL_STRUCTURE_PIGEON, "POST", postData);//得到返回字符流
string result = Encoding.UTF8.GetString(responseData);//解码
departmentList = JsonConvert.DeserializeObject<List<Department>>(result);
}
if (departmentList == null)
{
return new List<string>().ToArray();
}
else
{
var firstLevelDepartment = departmentList.SingleOrDefault(_ => _.Level == 1);
if (firstLevelDepartment == null)
{
return new List<string>().ToArray();
}
else
{
return new string[] { firstLevelDepartment.DepartmentId.ToString() };
}
}
}
示例15: UploadTextFile
/// <summary>
/// This method is used to upload a file to the specified URI.
/// </summary>
/// <param name="fileUrl">Specify the URL where the file will be uploaded to.</param>
/// <param name="fileName">Specify the name for the file to upload.</param>
/// <returns>Return true if the operation succeeds, otherwise return false.</returns>
public bool UploadTextFile(string fileUrl, string fileName)
{
WebClient client = new WebClient();
string fullFileUri = string.Format("{0}/{1}", fileUrl, fileName);
try
{
byte[] contents = System.Text.Encoding.UTF8.GetBytes(Common.Common.GenerateResourceName(Site, "FileContent"));
client.Credentials = new NetworkCredential(Common.Common.GetConfigurationPropertyValue("UserName1", Site), Common.Common.GetConfigurationPropertyValue("Password1", Site), Common.Common.GetConfigurationPropertyValue("Domain", Site));
if (fullFileUri.StartsWith("HTTPS", System.StringComparison.OrdinalIgnoreCase))
{
Common.Common.AcceptServerCertificate();
}
client.UploadData(fullFileUri, "PUT", contents);
}
catch (System.Net.WebException ex)
{
Site.Log.Add(
LogEntryKind.Debug,
string.Format("Cannot upload the file to the full URI {0}, the exception message is {1}", fullFileUri, ex.Message));
return false;
}
finally
{
if (client != null)
{
client.Dispose();
}
}
return true;
}
开发者ID:OfficeDev,项目名称:Interop-TestSuites,代码行数:40,代码来源:MS-FSSHTTP-FSSHTTPBManagedCodeSUTControlAdapter.cs