private void upload_context(object param) { IDataObject data = (IDataObject)param; if (data.GetFormats().Length <= 0) { return; } WebClient _webClient = new WebClient(); _webClient.Credentials = new NetworkCredential(webdav_username, webdav_password); if (data.GetDataPresent(typeof(string))) //如果是文本 { string context = (string)data.GetData(typeof(string)); if (context.StartsWith("http://") || context.StartsWith("https://")) { WebClient mywebclient = new WebClient(); byte[] temp = mywebclient.DownloadData(context); if (bytes_is_bitmap(temp)) //如果上传的时图片连接则自动下载图片 { Uri _dist_path_1 = new Uri(webdav_server + "图片链接-" + guid.ToString("N") + ".txt"); _webClient.UploadString(_dist_path_1, "PUT", context); Uri _dist_path_2 = new Uri(webdav_server + "图片-" + guid.ToString("N") + ".bmp"); _webClient.UploadDataAsync(_dist_path_2, "PUT", temp); return; } } Uri _dist_path = new Uri(webdav_server + "文字-" + guid.ToString("N") + ".txt"); _webClient.UploadString(_dist_path, "PUT", context); } else if (data.GetDataPresent(typeof(Bitmap))) //如果是图片 { Bitmap context = (Bitmap)data.GetData(typeof(Bitmap)); Uri _dist_path = new Uri(webdav_server + "图片-" + guid.ToString("N") + ".bmp"); MemoryStream ms = new MemoryStream(); context.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp); byte[] bytes = ms.GetBuffer(); ms.Close(); _webClient.UploadDataAsync(_dist_path, "PUT", bytes); } else if (data.GetDataPresent(DataFormats.FileDrop)) //如果是文件 { string[] files = (string [])data.GetData(DataFormats.FileDrop); Clipboard.GetFileDropList().CopyTo(files, 0); foreach (string file in files) //需要注意的是,如果上传的文件中有文件夹,文件夹结构将不会被保留 { string filename = Path.GetFileNameWithoutExtension(file); string ext = Path.GetExtension(file); Uri _dist_path = new Uri(webdav_server + filename + "-文件-" + guid.ToString("N") + ext); _webClient.UploadFileAsync(_dist_path, "PUT", file); } } _webClient.Dispose(); }
public void RetrieveStationsAsync() { try { WebClient client = new WebClient(); client.Headers.Add("content-type", "text-xml"); client.UploadDataCompleted += new UploadDataCompletedEventHandler(RetrieveStations_UploadDataCompleted); Uri uri = new Uri(String.Format(BASE_URL_LID, _rid, _lid, "getStations")); List <object> parameters = new List <object>(); parameters.Add(GetTimestamp()); parameters.Add(_authenticationToken); string xml = GetXml("station.getStations", parameters); string encryptedXml = EncryptionHelper.EncryptString(xml); client.UploadDataAsync(uri, "POST", System.Text.Encoding.ASCII.GetBytes(encryptedXml)); } catch (Exception exception) { if (ExceptionReceived != null) { ExceptionReceived(this, new EventArgs <Exception>(exception)); } } }
/// <summary> /// 处理发送消息包 /// </summary> public override void ProcessSendPacket() { if (mSendQueue == null) { return; } try { if (!IsConnect()) { return; } mCanSend = false; PBPacket packet = mSendQueue.Dequeue(); byte[] bytes = packet.Encoder(); // 发送消息 WebClient webClient = new WebClient(); webClient.UploadDataCompleted += ProcessReceiveThreadCallback; webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); webClient.UploadDataAsync(new Uri(mReqUrl), mHttpMethod, bytes); // LogUtils.Log("Http Send: " + JsonConvert.SerializeObject(msg), LType.Normal); } catch (Exception ex) { new Exception("not achieve " + ex.ToString()); } }
/// <summary> /// Uploads the file. /// </summary> public static void UploadFile() { DebugLevelController.Log("Path: " + FilePath, 1); DebugLevelController.Log("Username: "******"Pass: "******"Host: ftp://" + FTPHost, 1); //end uploading /*t2_ = new Thread(UploadThread); * if (!t2_.IsAlive) * t2_.Start();*/ StaticCoroutine.Start(UploadThread()); EditorLogGenerator.GenerateLog("Upload started"); shouldCheck = true; Uri uri2 = new Uri("ftp://" + FTPHost + "version.thln"); client2.Credentials = new System.Net.NetworkCredential(FTPUserName, FTPPassword); client2.UploadFileCompleted += new UploadFileCompletedEventHandler(OnFileUploadCompleted2); client2.UploadFileAsync(uri2, "STOR", Application.dataPath + "/../TheLauncher/version/version.thln"); EditorLogGenerator.GenerateLog("Version File Upload Started"); Uri uri3 = new Uri("ftp://" + FTPHost + "v.thln"); client3.Credentials = new System.Net.NetworkCredential(FTPUserName, FTPPassword); client3.UploadDataCompleted += new UploadDataCompletedEventHandler(OnFileUploadCompleted3); byte[] bytes3 = File.ReadAllBytes(Application.dataPath + "/../TheLauncher/version/v.thln"); client3.UploadDataAsync(uri3, "STOR", bytes3); EditorLogGenerator.GenerateLog("File List Upload Started"); }
/// <summary> /// Post异步请求 /// </summary> /// <param name="url">Url地址</param> /// <param name="postStr">请求Url数据</param> /// <param name="callBackUploadDataCompleted">回调事件</param> /// <param name="encode"></param> public static void HttpPostAsync(string url, string postStr = "", UploadDataCompletedEventHandler callBackUploadDataCompleted = null, Encoding encode = null, Dictionary <string, string> heards = null) { var webClient = new WebClient { Encoding = Encoding.UTF8 }; if (encode != null) { webClient.Encoding = encode; } var sendData = Encoding.GetEncoding("UTF-8").GetBytes(postStr); webClient.Headers.Add("Content-Type", "application/json"); webClient.Headers.Add("ContentLength", sendData.Length.ToString(CultureInfo.InvariantCulture)); if (heards != null) { foreach (var item in heards) { webClient.Headers.Add(item.Key, item.Value); } } if (callBackUploadDataCompleted != null) { webClient.UploadDataCompleted += callBackUploadDataCompleted; } webClient.UploadDataAsync(new Uri(url), "POST", sendData); }
/// <summary> /// <paramref name="address"/>에 <paramref name="data"/>를 비동기적으로 전송합니다. /// </summary> /// <param name="webClient"></param> /// <param name="address">데이타를 전송할 주소</param> /// <param name="method">데이타 전송 방법 (HTTP는 POST, FTP는 STOR)</param> /// <param name="data">전송할 데이타</param> /// <returns></returns> public static Task <byte[]> UploadDataTask(this WebClient webClient, Uri address, string method, byte[] data) { webClient.ShouldNotBeNull("webClient"); address.ShouldNotBeNull("address"); data.ShouldNotBeNull("data"); if (IsDebugEnabled) { log.Debug("지정된 주소에 데이타를 비동기 방식으로 전송합니다... address=[{0}], method=[{1}]", address.AbsoluteUri, method); } var tcs = new TaskCompletionSource <byte[]>(address); UploadDataCompletedEventHandler handler = null; handler = (s, e) => EventAsyncPattern.HandleCompletion(tcs, e, () => e.Result, () => webClient.UploadDataCompleted -= handler); webClient.UploadDataCompleted += handler; try { webClient.UploadDataAsync(address, method ?? "POST", data, tcs); } catch (Exception ex) { if (log.IsWarnEnabled) { log.Warn("WebClient를 이용하여 데이타를 비동기 전송에 실패했습니다. address=[{0}]" + address.AbsoluteUri); log.Warn(ex); } webClient.UploadDataCompleted -= handler; tcs.TrySetException(ex); } return(tcs.Task); }
private static void TestRequestLocal() { string searchStr = "C# is a language for developers!This is test for C# and Java!"; Uri uri = new Uri("http://127.0.0.1:8888"); string url = "http://127.0.0.1:8888"; WebClient wc = new WebClient(); wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); wc.Encoding = Encoding.UTF8; wc.UploadDataCompleted += new UploadDataCompletedEventHandler(OnUploadDataCompleted); //byte[] upBytes = wc.UploadData(url, "POST", Encoding.Default.GetBytes(searchStr)); C2S_GetStudentInfo student = BuildStudent(); MemoryStream s = new MemoryStream(); ProtoBuf.Serializer.Serialize(s, student); try { byte[] buff = StreamToByteArray(s); Console.WriteLine("send len: " + buff.Length); wc.UploadDataAsync(uri, "POST", buff); } catch (WebException we) { Console.WriteLine("Exception:" + we.ToString()); } }
public void UploadGuildBamTimestamp() { var ts = CurrentServerTime - new DateTime(1970, 1, 1); var time = (long)ts.TotalSeconds; var sb = new StringBuilder(BaseUrl); sb.Append("?srv="); sb.Append(PacketProcessor.Server.ServerId); sb.Append("®="); sb.Append(CurrentRegion); sb.Append("&post"); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; var c = new WebClient(); c.Headers.Set("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36"); try { c.UploadDataAsync(new Uri(sb.ToString()), new byte[] { }); } catch { ChatWindowManager.Instance.AddTccMessage("Failed to upload guild bam info."); } }
public static void CallApi(EnumApi api, UploadDataCompletedEventHandler strHandler, object obj) { using (WebClient client = new WebClient()) { #region 消息头 client.Headers["Type"] = "Post"; client.Headers.Add("Content-Type", ConfigurationManager.AppSettings["Content-Type"]); client.Encoding = Encoding.UTF8; #endregion #region PostData string postData = JsonConvert.SerializeObject(obj); byte[] bytes = Encoding.UTF8.GetBytes(postData); client.Headers.Add("ContentLength", postData.Length.ToString()); #endregion #region 回调处理 client.UploadDataCompleted += strHandler; #endregion string uriString = GetConfigValue(api); if (!string.IsNullOrEmpty(uriString)) { client.UploadDataAsync(new Uri(GetConfigValue(api)), bytes); } } }
public static void ProcessQueue() { if (!_isHandlingRequest && _packets.Count > 0) { lock (_syncRoot) { if (_sasProvider == null) { _sasProvider = new SharedAccessSignatureTokenProvider(CommonConfiguration.Instance.BackboneConfiguration.IssuerName, CommonConfiguration.Instance.BackboneConfiguration.IssuerSecret, new TimeSpan(1, 0, 0)); } _isHandlingRequest = true; var packet = _packets.Dequeue(); var content = Encoding.Default.GetBytes(DatacontractSerializerHelper.Serialize <GamePacket>(packet)); using (WebClient webClient = new WebClient()) { var token = _sasProvider.GetToken(CommonConfiguration.Instance.BackboneConfiguration.GetRealm(), "POST", new TimeSpan(1, 0, 0)); webClient.Headers[HttpRequestHeader.Authorization] = token.TokenValue; // add the properties var collection = new NameValueCollection(); collection.Add(GamePacket.VERSION, GamePacket.Namespace); webClient.Headers.Add(collection); webClient.UploadDataCompleted += WebClient_UploadDataCompleted; webClient.UploadDataAsync(new Uri(CommonConfiguration.Instance.BackboneConfiguration.GetServiceMessagesAddress(packet.Queue)), "POST", content); } } } }
/// <summary> /// 以用户名或邮箱查询用户 /// </summary> /// <param name="users"></param> /// <returns></returns> public Dictionary <string, string> IsAdmitted(AspNetUser users, UploadDataCompletedEventHandler callback) { try { WebClient client = new WebClient { Encoding = Encoding.UTF8 }; StringBuilder postData = new StringBuilder(); postData.Append($"Id={users.UserName} "); postData.Append($"&pass={users.PasswordHash}"); byte[] sendData = Encoding.UTF8.GetBytes(postData.ToString()); client.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); client.Headers.Add("ContentLength", sendData.Length.ToString()); //var recData = client.UploadData(ConfigurationManager.AppSettings["loginVerification"], "POST",sendData); client.UploadDataAsync(new Uri(ConfigurationManager.AppSettings["loginVerification"]), "POST", sendData); client.UploadDataCompleted += callback; // string aaaa = Encoding.UTF8.GetString(aa); //client.Dispose(); return(null); } catch (Exception ex) { return(new Dictionary <string, string> { { "Errors", ex.Message } }); } }
public IEnumerator Detect(Texture2D texture) { bool finished = false; bool isQR = false; //StartCoroutine( Fetch()); //Texture2D texture = (Texture2D)Resources.Load("funeral-qr-code", typeof(Texture2D)); using (WebClient client = new WebClient()) { client.Headers.Add("Prediction-Key", "4c4370fcac684e9687e46121d7dacc30"); client.Headers.Add("Content-Type", "application/octet-stream"); client.UploadDataCompleted += (object sender, UploadDataCompletedEventArgs e) => { string response_string = System.Text.Encoding.Default.GetString(e.Result); TrainedResponse response_object = JsonUtility.FromJson <TrainedResponse>(response_string); if (response_object.Predictions.Count > 0) { Prediction most_likely = response_object.Predictions[0]; isQR = (most_likely.Tag == "QR" && most_likely.Probability >= 0.7f); } Debug.Log("isQR? " + isQR); finished = true; }; client.UploadDataAsync(new System.Uri("https://southcentralus.api.cognitive.microsoft.com/customvision/v1.0/Prediction/02747810-f650-4ed2-9344-625bd93dd126/image"), texture.EncodeToPNG()); yield return(new WaitUntil(() => finished)); } }
// put private void put(string upToken, string saveKey = null, string mimeType = null, bool crc32 = false, NameValueCollection xVars = null) { upInfo info = readyUp(upToken, this.streamReader, saveKey, mimeType, crc32, xVars); WebClient client = new WebClient(); client.Headers.Add("Authorization", "UpToken " + upToken); client.UploadProgressChanged += (o, e) => { onProgressing(o, new UploadProgressEventArgs(fileSize, e.BytesSent)); }; client.UploadDataCompleted += (o, e) => { if (!e.Cancelled) { string jsonStr = Encoding.UTF8.GetString(e.Result); Dictionary <string, string> res = JsonConvert.DeserializeObject <Dictionary <string, string> >(jsonStr); onFinished(this, new UploadFinishedArgs(res)); } else { //TO-DO } }; try{ uping = true; client.UploadDataAsync(new Uri(info.upUrl), "POST", info.data); }catch (Exception e) { onFailed(this, new UploadFailedEventArgs(e.ToString())); } }
/// <summary> /// Http同步Post异步请求 /// </summary> /// <param name="url">Url地址</param> /// <param name="postStr">请求Url数据</param> /// <param name="callBackUploadDataCompleted">回调事件</param> /// <param name="encode"></param> public void HttpPostAsync(string url, string postStr = "", UploadDataCompletedEventHandler callBackUploadDataCompleted = null, Encoding encode = null) { try { var webClient = new WebClient { Encoding = Encoding.UTF8 }; if (encode != null) { webClient.Encoding = encode; } var sendData = Encoding.GetEncoding("GB2312").GetBytes(postStr); webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); webClient.Headers.Add("ContentLength", sendData.Length.ToString(CultureInfo.InvariantCulture)); if (callBackUploadDataCompleted != null) { webClient.UploadDataCompleted += callBackUploadDataCompleted; } webClient.UploadDataAsync(new Uri(url), "POST", sendData); } catch (Exception e) { } }
public void SynchronizeFilesAsync() { if (UseCompression == false) { throw new ArgumentException("Asynchronous synchronizing currently only works with UseCompression = true."); } cancel_set = false; string filelist = CreateFileList(); OnSynchronizeStepStarting(SynchonizeStep.CompareWithServer, 0, 0, TimeSpan.Zero); if (cancel_set) { return; } // Upload the file list to the server WebClient wc = new WebClient(); string url = string.Format("/session/{0}/filelist", ID); byte[] buffer = Encoding.ASCII.GetBytes(filelist); running_request = wc; wc.UploadDataCompleted += new UploadDataCompletedEventHandler(FileList_UploadDataCompleted); wc.UploadDataAsync(Connection.CreateUri(url), buffer); }
public void SubmitFeedbackAsync(Song song, Ratings rating) { try { WebClient client = new WebClient(); client.Headers.Add("content-type", "text-xml"); client.UploadDataCompleted += new UploadDataCompletedEventHandler(SubmitFeedback_UploadDataCompleted); Uri uri = new Uri(String.Format(BASE_URL_LID, _rid, _lid, "addFeedback")); List <object> parameters = new List <object>(); parameters.Add(GetTimestamp()); parameters.Add(_authenticationToken); parameters.Add(song.StationId); parameters.Add(song.MusicId); parameters.Add(song.UserSeed); parameters.Add(String.Empty); //TestStrategy--wtf? parameters.Add(rating == Ratings.Like); parameters.Add(false); //IsCreatorQuickMix parameters.Add(song.SongType); string xml = GetXml("station.addFeedback", parameters); string encryptedXml = EncryptionHelper.EncryptString(xml); client.UploadDataAsync(uri, "POST", System.Text.Encoding.ASCII.GetBytes(encryptedXml)); } catch (Exception exception) { if (ExceptionReceived != null) { ExceptionReceived(this, new EventArgs <Exception>(exception)); } } }
/// <summary>Uploads data to the specified resource, asynchronously.</summary> /// <param name="webClient">The WebClient.</param> /// <param name="address">The URI to which the data should be uploaded.</param> /// <param name="method">The HTTP method that should be used to upload the data.</param> /// <param name="data">The data to upload.</param> /// <returns>A Task containing the data in the response from the upload.</returns> public static Task <byte[]> UploadDataTask(this WebClient webClient, Uri address, string method, byte [] data) { // Create the task to be returned var tcs = new TaskCompletionSource <byte[]>(address); // Setup the callback event handler UploadDataCompletedEventHandler handler = null; handler = (sender, e) => EAPCommon.HandleCompletion(tcs, e, () => e.Result, () => webClient.UploadDataCompleted -= handler); webClient.UploadDataCompleted += handler; // Start the async work try { webClient.UploadDataAsync(address, method, data, tcs); } catch (Exception exc) { // If something goes wrong kicking off the async work, // unregister the callback and cancel the created task webClient.UploadDataCompleted -= handler; tcs.TrySetException(exc); } // Return the task that represents the async operation return(tcs.Task); }
/// <summary> /// Upload byte array content asynchron. /// Progress is signaled via UploadProgressChanged and UploadDataCompleted event. /// </summary> /// <param name="data">Byte array</param> public void UploadDataEvents(byte[] data) { lock (_syncRootAsync) { // Abort other operation. if (_gettAsync != null) { _gettAsync.DownloadDataCompleted -= Gett_DownloadDataCompleted; _gettAsync.DownloadFileCompleted -= Gett_DownloadFileCompleted; _gettAsync.DownloadProgressChanged -= Gett_DownloadProgressChanged; _gettAsync.UploadDataCompleted -= Gett_UploadDataCompleted; _gettAsync.UploadFileCompleted -= Gett_UploadFileCompleted; _gettAsync.UploadProgressChanged -= Gett_UploadProgressChanged; if (_gettAsync.IsBusy) { _gettAsync.CancelAsync(); } } // GET request _gettAsync = new WebClient(); _gettAsync.UploadDataCompleted += Gett_UploadDataCompleted; _gettAsync.UploadProgressChanged += Gett_UploadProgressChanged; _gettAsync.UploadDataAsync(new Uri(_gettFileInfo.Upload.PutUrl), "PUT", data); } }
/// <summary> /// 通过ftp上传字节数据到服务器 /// </summary> /// <param name="data">字节数据</param> /// <param name="fileName">存储到服务器的文件名,带后缀</param> /// <param name="callBack">完成回调函数</param> /// <param name="progress">进度改变回调函数</param> public void UploadData(byte[] data, string fileName, WillFtpUploadCallBack callBack, WillFtpUploadProgressChangedEvent proEvent = null) { if (string.IsNullOrEmpty(m_FTPHost) || string.IsNullOrEmpty(m_FTPUserName)) { WDebuger.LogError("未进行初始化,请检查!"); return; } if (string.IsNullOrEmpty(fileName)) { WDebuger.LogError("存储文件名不能为空,请检查! 参数:" + fileName); } m_FTPUploadCallBack = callBack; m_UploadProgressEvent = proEvent; m_UploadDataByteCount = data.Length; m_Progreess = 0; m_WebClient = new WebClient(); m_WebClient.Encoding = Encoding.UTF8; Uri uri = new Uri(m_FTPHost + fileName); m_WebClient.UploadDataCompleted += new UploadDataCompletedEventHandler(OnDataUploadCompleted); m_WebClient.UploadProgressChanged += new UploadProgressChangedEventHandler(OnDataUploadProgressChanged); m_WebClient.Credentials = new NetworkCredential(m_FTPUserName, m_FTPPasswork); m_WebClient.UploadDataAsync(uri, "STOR", data); }
/// <summary> /// 异步提交(不需要接受返回值) /// </summary> /// <param name="url"></param> /// <param name="data"></param> /// <param name="wc"></param> /// <param name="headers"></param> /// <param name="exception">异常处理</param> public static void UploadDataAsync(string url, byte[] data, WebClient wc = null, Dictionary <string, string> headers = null, Action <WebException> exception = null) { using (wc ??= CreateWebClient(url)) { try { if (headers != null) { foreach (KeyValuePair <string, string> header in headers) { wc.Headers[header.Key] = header.Value; } } if (!wc.Headers.AllKeys.Contains("Content-Type")) { wc.Headers.Add(HttpRequestHeader.ContentType, "text/plain;charset=UTF-8"); } wc.UploadDataAsync(new Uri(url), data); } catch (WebException ex) { if (exception != null) { exception(ex); } } } }
public void UploadGuildBamTimestamp() { var sb = new StringBuilder(BaseUrl); sb.Append("?srv="); sb.Append(SessionManager.Server.ServerId); sb.Append("®="); sb.Append(CurrentRegion); sb.Append("&post"); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; var c = new WebClient(); c.Headers.Set("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36"); try { c.UploadDataAsync(new Uri(sb.ToString()), new byte[] { }); } catch { ChatWindowManager.Instance.AddTccMessage("Failed to upload guild BAM info."); WindowManager.FloatingButton.NotifyExtended("Guild BAM", "Failed to upload guild BAM info.", NotificationType.Error); } }
protected override void TransferChunk(MegaChunk chunk, Action transferCompleteFn) { if (chunk.Handle.SkipChunks) { transferCompleteFn(); return; } var wc = new WebClient(); wc.Proxy = transport.Proxy; chunk.Handle.ChunkTransferStarted(wc); wc.UploadDataCompleted += (s, e) => { chunk.Handle.ChunkTransferEnded(wc); transferCompleteFn(); if (e.Cancelled) { return; } if (e.Error != null) { chunk.Handle.BytesTransferred(0 - chunk.transferredBytes); EnqueueTransfer(new List <MegaChunk> { chunk }, true); } else { OnUploadedChunk(chunk, e); } }; wc.UploadProgressChanged += (s, e) => OnUploadedBytes(chunk, e.BytesSent); var url = String.Format(((UploadHandle)chunk.Handle).UploadUrl + "/{0}", chunk.Offset); wc.UploadDataAsync(new Uri(url), chunk.Data); }
private void AuthenticateListenerAsync() { try { WebClient client = new WebClient(); client.Headers.Add("content-type", "text-xml"); client.UploadDataCompleted += new UploadDataCompletedEventHandler(AuthenticateListener_UploadDataCompleted); Uri uri = new Uri(String.Format(BASE_URL_RID, _rid, "authenticateListener")); List <object> parameters = new List <object>(); parameters.Add(GetTimestamp()); parameters.Add(_username); parameters.Add(_password); parameters.Add("html5tuner"); //?? parameters.Add(String.Empty); //?? parameters.Add(String.Empty); //?? parameters.Add("HTML5"); //?? parameters.Add(true); //?? string xml = GetXml("listener.authenticateListener", parameters); string encryptedXml = EncryptionHelper.EncryptString(xml); client.UploadDataAsync(uri, "POST", System.Text.Encoding.ASCII.GetBytes(encryptedXml)); } catch (Exception exception) { if (ExceptionReceived != null) { ExceptionReceived(this, new EventArgs <Exception>(exception)); } } }
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); }); }
private void DownloadData() { Title = titledef + "Downloading..."; wc = new WebClient(); wc.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore); wc.UploadDataCompleted += Wc_UploadDataCompleted; wc.UploadDataAsync(new Uri("http://sesoc.global/society_mypage/selectAllSchedule"), new byte[] { }); }
public static void AsyncHttpRequest(string maiurl, string paramurl) { using (WebClient client = new WebClient()) { var Postbyte = Encoding.ASCII.GetBytes(paramurl); client.UploadDataAsync(new Uri(maiurl), "POST", Postbyte); } }
/// <summary> /// 连接服务器,并上传文件 /// </summary> /// <param name="info">文件信息</param> /// <param name="raw"></param> /// <param name="retry"></param> public void Upload(FileInformation info, byte[] raw, bool retry = true) { string fileName = info.FileName.Replace(@"\", "/"); // 为文件名添加 .gz 后缀 if (fileName != "AutoPatcher.gz" && fileName != "PList.gz") { fileName += ".gz"; } using (WebClient client = new WebClient()) { // 初始化连接并登录 client.Credentials = new NetworkCredential(Settings.Login, Settings.Password); byte[] data = !retry ? raw : raw; info.Compressed = data.Length; // 数据上传进度 client.UploadProgressChanged += (o, e) => { int value = (int)(100 * e.BytesSent / e.TotalBytesToSend); progressBar2.Value = value > progressBar2.Maximum ? progressBar2.Maximum : value; FileLabel.Text = fileName; SizeLabel.Text = string.Format("{0} KB / {1} KB", e.BytesSent / 1024, e.TotalBytesToSend / 1024); SpeedLabel.Text = ((double)e.BytesSent / 1024 / _stopwatch.Elapsed.TotalSeconds).ToString("0.##") + " KB/s"; }; // 数据上传完成 client.UploadDataCompleted += (o, e) => { _completedBytes += info.Length; if (e.Error != null && retry) { CheckDirectory(Path.GetDirectoryName(fileName)); Upload(info, data, false); return; } if (info.FileName == PatchFileName) { FileLabel.Text = "完成..."; SizeLabel.Text = "完成..."; SpeedLabel.Text = "完成..."; return; } progressBar1.Value = (int)(_completedBytes * 100 / _totalBytes) > 100 ? 100 : (int)(_completedBytes * 100 / _totalBytes); BeginUpload(); }; _stopwatch = Stopwatch.StartNew(); client.UploadDataAsync(new Uri(Settings.Host + fileName), data); } }
/// <summary> /// Send the book to a client over local network, typically WiFi (at least on Android end). /// This is currently called on the UDPListener thread. /// Enhance: if we spin off another thread to do the transfer, especially if we create the file /// and read it into memory once and share the content, we can probably serve multiple /// requesting devices much faster. Currently, we are only handling one request at a time, /// since we pause advertising while sending and ignore requests that come in during sending. /// If the user switches away from the Android tab while a transfer /// is in progress, the thread will continue and complete the request. Quitting Bloom /// is likely to leave the transfer incomplete. /// </summary> /// <param name="book"></param> /// <param name="androidIpAddress"></param> /// <param name="androidName"></param> private void StartSendBookToClientOnLocalSubNet(Book.Book book, string androidIpAddress, string androidName, Color backColor) { // Locked in case more than one thread at a time can handle incoming packets, though I don't think // this is true. Also, Stop() on the main thread cares whether _wifiSender is null. lock (this) { // We only support one send at a time. If we somehow get more than one request, we ignore the other. // The device will retry soon if still listening and we are still advertising. if (_wifiSender != null) // indicates transfer in progress { return; } // now THIS transfer is 'in progress' as far as any thread checking this is concerned. _wifiSender = new WebClient(); } _wifiSender.UploadDataCompleted += (sender, args) => { // Runs on the async transfer thread AFTER the transfer initiated below. if (args.Error != null) { ReportException(args.Error); } // Should we report if canceled? Thinking not, we typically only cancel while shutting down, // it's probably too late for a useful report. // To avoid contention with Stop(), which may try to cancel the send if it finds // an existing wifiSender, and may destroy the advertiser we are trying to restart. lock (this) { Debug.WriteLine($"upload completed, sender is {_wifiSender}, cancelled is {args.Cancelled}"); if (_wifiSender != null) // should be null only in a desperate abort-the-thread situation. { _wifiSender.Dispose(); _wifiSender = null; } if (_wifiAdvertiser != null) { _wifiAdvertiser.Paused = false; } } }; // Now we actually start the send...but using an async API, so there's no long delay here. PublishToAndroidApi.SendBook(book, _bookServer, null, (publishedFileName, bloomDPath) => { var androidHttpAddress = "http://" + androidIpAddress + ":5914"; // must match BloomReader SyncServer._serverPort. _wifiSender.UploadDataAsync(new Uri(androidHttpAddress + "/putfile?path=" + Uri.EscapeDataString(publishedFileName)), File.ReadAllBytes(bloomDPath)); }, _progress, (publishedFileName, bookTitle) => _progress.GetMessageWithParams(id: "Sending", comment: "{0} is the name of the book, {1} is the name of the device", message: "Sending \"{0}\" to device {1}", parameters: new object[] { bookTitle, androidName }), null, backColor); PublishToAndroidApi.ReportAnalytics("wifi", book); }
public void Send(string fileName, string content) { using (var client = new WebClient()) { // client.UploadDataCompleted += UploadDataCompleted; byte[] msgBytes = BuildMessage(fileName, content); client.UploadDataAsync(loggerApi, "POST", msgBytes, client); } }
public static void UploadMultipartAsync(this WebClient client, Uri address, string method, MultipartFormBuilder multipart, object userToken) { client.Headers.Add(HttpRequestHeader.ContentType, multipart.ContentType); using (var stream = multipart.GetStream()) { client.UploadDataAsync(address, method, stream.ToArray(), userToken); } }
public static void CheckNewVersionAvailable() { if (EditorPrefs.HasKey(lastVersionKey)) { lastVersionID = EditorPrefs.GetString(lastVersionKey); if (CompareVersions()) { hasNewVersion = true; return; } } const long ticksInHour = 36000000000; if (EditorPrefs.HasKey(lastVersionCheckKey)) { long lastVersionCheck = EditorPrefs.GetInt(lastVersionCheckKey) * ticksInHour; if (DateTime.Now.Ticks - lastVersionCheck < 24 * ticksInHour) { return; } } EditorPrefs.SetInt(lastVersionCheckKey, (int)(DateTime.Now.Ticks / ticksInHour)); if (EditorPrefs.HasKey(channelKey)) channel = (OnlineMapsUpdateChannel)EditorPrefs.GetInt(channelKey); else channel = OnlineMapsUpdateChannel.stable; if (channel == OnlineMapsUpdateChannel.stablePrevious) channel = OnlineMapsUpdateChannel.stable; WebClient client = new WebClient(); client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; client.UploadDataCompleted += delegate(object sender, UploadDataCompletedEventArgs response) { if (response.Error != null) { Debug.Log(response.Error.Message); return; } string version = Encoding.UTF8.GetString(response.Result); try { string[] vars = version.Split(new[] { '.' }); string[] vars2 = new string[4]; while (vars[1].Length < 8) vars[1] += "0"; vars2[0] = vars[0]; vars2[1] = int.Parse(vars[1].Substring(0, 2)).ToString(); vars2[2] = int.Parse(vars[1].Substring(2, 2)).ToString(); vars2[3] = int.Parse(vars[1].Substring(4)).ToString(); version = string.Join(".", vars2); } catch (Exception) { Debug.Log("Automatic check for Online Maps updates: Bad response."); return; } lastVersionID = version; hasNewVersion = CompareVersions(); EditorApplication.update += SetLastVersion; }; client.UploadDataAsync(new Uri("http://infinity-code.com/products_update/getlastversion.php"), "POST", Encoding.UTF8.GetBytes("c=" + (int)channel + "&package=" + WWW.EscapeURL(packageID))); }
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); }); }
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; }); }