/// <summary> /// Sends a request to the remote server. /// </summary> /// <param name="requestContent">The content of the request to send as a stream.</param> /// <returns>The response from the server, as a stream.</returns> public async Task <Stream> SendRequest(Stream requestContent) { HttpContent content = null; try { content = new StreamContent(requestContent); if (!String.IsNullOrEmpty(_ContentType)) { content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(_ContentType); content.Headers.ContentType.CharSet = _CharSet; } } catch { content?.Dispose(); throw; } var response = await _Client.PostAsync(_ServerAddress, content).ConfigureAwait(false); response.EnsureSuccessStatusCode(); return(await response.Content.ReadAsStreamAsync().ConfigureAwait(false)); }
public void UploadExtensionLibraryAsync(string selectedFileName, byte[] fileContents, ObservableCollection <string> assemblies, object userState) { Uri uri = CreateRestRequest("Extensions/Upload"); var assembliesString = assemblies != null?string.Join(",", assemblies) : null; var content = new MultipartFormDataContent(); var ms = new MemoryStream(fileContents); var fileContent = new StreamContent(ms); // Specify the content disposition and content type - without this the form data will not // be included in the Request object in .NET 2.0 app pools fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "\"files\"", FileName = "\"" + selectedFileName + "\"" }; fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-silverlight-app"); content.Add(fileContent); var stringContent = new StringContent(assembliesString); // Need to specify the content disposition and content type for .NET 2.0 compatibility here, too stringContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "\"assemblies\"" }; stringContent.Headers.ContentType = new MediaTypeHeaderValue("text/plain"); content.Add(stringContent); var client = new HttpClient(); client.PostAsync(uri, content).ContinueWith(t => { stringContent.Dispose(); fileContent.Dispose(); ms.Dispose(); content.Dispose(); if (t.IsCanceled) { return; } if (t.Exception != null) { var errorDisplay = new ErrorDisplay(); // Attempt to get the stack trace with IL offsets string stackTraceIL = t.Exception.StackTraceIL(); ErrorData data = new ErrorData() { Message = t.Exception.Message, StackTrace = !string.IsNullOrEmpty(stackTraceIL) ? stackTraceIL : t.Exception.StackTrace }; errorDisplay.DataContext = data; // Size the error UI double width = Application.Current.RootVisual.RenderSize.Width * 0.67; errorDisplay.Width = width > errorDisplay.MaxWidth ? errorDisplay.MaxWidth : width; errorDisplay.Completed += (o, a) => BuilderApplication.Instance.HideWindow(errorDisplay); // Show the error BuilderApplication.Instance.ShowWindow(Strings.ErrorOccured, errorDisplay, false, null, null); } if (UploadExtensionLibraryCompleted != null) { UploadExtensionLibraryCompleted(this, new UploadExtensionLibraryCompletedEventArgs() { Error = t.Exception, UserState = userState, }); } }, TaskScheduler.FromCurrentSynchronizationContext()); }
public void Dispose() => _content.Dispose();
protected virtual HttpContent Parse(T message, System.Net.Http.Headers.HttpHeaders headers, string data) { if (data == null) { throw new ArgumentNullException("data"); } if (data.Length == 0) { throw new ArgumentException("data cannot be an empty string.", "data"); } if (!LineTerminators.Any(data.Contains)) { throw new ArgumentException("data is not a valid request, it does not contain any CRLF/LF terminators.", "data"); } HttpContent retVal = null; try { var contentStream = new System.IO.MemoryStream(); try { retVal = new StreamContent(contentStream); var lines = data.Split(LineTerminators, StringSplitOptions.None); //First line is the 'request' line containing http protocol details like method, uri, http version etc. ParseStatusLine(lines[0], message); int lineIndex = ParseHeaders(headers, retVal.Headers, lines); if (lineIndex < lines.Length - 1) { //Read rest of any remaining data as content. if (lineIndex < lines.Length - 1) { //This is inefficient in multiple ways, but not sure of a good way of correcting. Revisit. var body = System.Text.UTF8Encoding.UTF8.GetBytes(String.Join(null, lines, lineIndex, lines.Length - lineIndex)); contentStream.Write(body, 0, body.Length); contentStream.Seek(0, System.IO.SeekOrigin.Begin); } } } catch { if (contentStream != null) { contentStream.Dispose(); } throw; } } catch { if (retVal != null) { retVal.Dispose(); } throw; } return(retVal); }
///上传签名 /// </summary> public CommonResponse UploadSignature(object eventData) { var ret = new CommonResponse("0"); var jsData = JsonUtil.SerializeObject(eventData); var request = JsonUtil.DeserializeObject <CommonRequest>(jsData); ret.Ips = request.Ips; if (!File.Exists(request.Data.ToString())) { ret.Code = ErrorCode.FILE_NOTFOUND; LogUtil.HWLogger.UI.Error("Upload Signatur failed: File path error,error path " + request.Data.ToString()); return(ret); } var fusionDirector = FusionDirectorWorker.Instance.FindByIP(request.Ips[0]); if (fusionDirector == null) { ret.Code = ErrorCode.NET_FD_NOFOUND; LogUtil.HWLogger.UI.Error("Upload Signatur failed: not found Fd" + request.Ips[0].ToString()); return(ret); } AggregateExceptionCatched2 += new EventHandler <AggregateExceptionArgs>(Program_AggregateExceptionCatched2); TokenSource2 = new CancellationTokenSource(); Task.Factory.StartNew(() => { try { byte[] bytes = System.Text.Encoding.UTF8.GetBytes(fusionDirector.LoginAccount + ":" + fusionDirector.LoginPwd); var authStr = "Basic " + Convert.ToBase64String(bytes); var remoteUrl = "https://" + fusionDirector.HostIP + ":" + fusionDirector.Port + "/redfish/v1" + request.Endpoint; //默认忽略证书 ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; //兼容所有ssl协议 ServicePointManager.SecurityProtocol = (SecurityProtocolType)(3072 | 768 | 192 | 48); var file = File.Open(request.Data.ToString(), FileMode.Open, FileAccess.Read); ret.Description = Math.Round((decimal)file.Length / (1024 * 1024), 0).ToString(); var fileContent = new StreamContent(file) { Headers = { ContentLength = file.Length, ContentType = new MediaTypeHeaderValue("application/octet-stream") } }; var formDataContent = new MultipartFormDataContent(); var fileName = file.Name.Substring(file.Name.LastIndexOf('\\') + 1); formDataContent.Add(fileContent, "tiFile", fileName); var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, remoteUrl); var progressContent = new ProgressableStreamContent(formDataContent, 4096 * 100, (sent, total) => { try { var Progress = Convert.ToInt32(Math.Round((decimal)sent / total, 2) * 100); FDBrowser.ExecuteScriptAsync("setUploadSignaturProgress", Progress);//设置升级包上传进度 setUploadSignaturProgress是UI js方法名称 Progress是进度 0-100 } catch (Exception ex) { AggregateExceptionArgs args = new AggregateExceptionArgs() { AggregateException = new AggregateException(ex) }; //使用主线程委托代理,处理子线程 异常 //这种方式没有阻塞 主线程或其他线程 AggregateExceptionCatched1?.Invoke(null, args); throw ex; } }); httpRequestMessage.Content = progressContent; httpRequestMessage.Headers.Add("Authorization", authStr); using (HttpClient httpClient = new HttpClient()) { var httpResponse = httpClient.SendAsync(httpRequestMessage, TokenSource2.Token).Result; var statusCode = ((int)httpResponse.StatusCode).ToString(); var resultStr = httpResponse.Content.ReadAsStringAsync().Result; LogUtil.HWLogger.API.Info("URL:" + remoteUrl + " Api Result:" + resultStr); ret.Data.Add(new Item() { Ip = fusionDirector.HostIP, Code = statusCode, Data = JsonConvert.DeserializeObject(resultStr) }); if (!statusCode.StartsWith("2")) { throw new BaseException(statusCode, ""); } fileContent.Dispose(); } file.Dispose(); } catch (BaseException ex) { LogUtil.HWLogger.UI.Error("Upload Signatur failed: ", ex); ret.Code = ex.Code; } catch (Exception ex) { LogUtil.HWLogger.UI.Error("Upload Signatur failed: ", ex); ret.Code = ErrorCode.SYS_UNKNOWN_ERR; AggregateExceptionArgs args = new AggregateExceptionArgs() { AggregateException = new AggregateException(ex) }; //使用主线程委托代理,处理子线程 异常 //这种方式没有阻塞 主线程或其他线程 AggregateExceptionCatched2?.Invoke(null, args); } ret.Ips = request.Ips; FDBrowser.ExecuteScriptAsync("uploadSignaturFileSuccess", JsonConvert.SerializeObject(ret));//执行升级包上传成功方法 uploadSignaturFileSuccess是UI js升级包上传成功方法 }); return(ret); }
/// <summary> /// 選択した画像ファイルをPDFに変換してMBAASにアップロードする。 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void ButtonUpload_Click(object sender, EventArgs e) { // PNG -> PDF 変換(ImageMagick呼び出し) string fromPng = @"D:\VisualStudio\HttpClientSample\kotoko.png"; string toJpeg = @"D:\VisualStudio\HttpClientSample\kotoko.jpeg"; string toPDF = @"D:\VisualStudio\HttpClientSample\kotoko.pdf"; Process convertProcess = null; try { // TODO : PNGから直接PDFを作成するとApacheがcontent-typeを削除する?? // TODO : 回避策として一旦JPEGに変換してからPDFに変換する // TODO : 課題:2回変換するので時間がかかる // プロセス情報設定(PNG -> JPEG) ProcessStartInfo processStartInfo = new ProcessStartInfo(); processStartInfo.FileName = @"D:\work\ImageMagick-7.0.10-Q16\convert.exe"; processStartInfo.Arguments = fromPng + " " + toJpeg; /* コマンドプロンプトを開かないようにする設定 */ processStartInfo.CreateNoWindow = true; processStartInfo.UseShellExecute = false; // プロセス実行 convertProcess = Process.Start(processStartInfo); convertProcess.WaitForExit(); // 戻り値チェック if (convertProcess.ExitCode != 0) { // PDF変換失敗 string message = String.Format("PDF変換エラー(PNG -> JPEG) : {0}", convertProcess.ExitCode); Console.WriteLine(message); MessageBox.Show(message); return; } // プロセス情報設定(JPEG -> PDF) processStartInfo.Arguments = toJpeg + " " + toPDF; // プロセス実行 convertProcess = Process.Start(processStartInfo); convertProcess.WaitForExit(); // 戻り値チェック if (convertProcess.ExitCode != 0) { // PDF変換失敗 string message = String.Format("PDF変換エラー(JPEG -> PDF) : {0}", convertProcess.ExitCode); Console.WriteLine(message); MessageBox.Show(message); return; } } catch (Exception exception) { // PDF変換失敗 string message = String.Format("PDF変換エラー : {0}", exception.Message); Console.WriteLine(message); MessageBox.Show(message); return; } finally { if (convertProcess != null) { convertProcess.Dispose(); } } // HTTP通信 using (HttpClient httpClient = new HttpClient()) { // HTTPリクエスト作成 HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, REST_API_UPLOAD_URL_BASE); // Basic認証(必要に応じて) //string username = @"username"; //string password = @"password"; //string authorizationParam = Convert.ToBase64String(Encoding.ASCII.GetBytes(String.Format("{0}:{1}", username, password))); //httpRequestMessage.Headers.Authorization = new AuthenticationHeaderValue("Basic", authorizationParam); // HTTPリクエストボディ作成 /* Multipart ContentにPDFを設定 */ MultipartFormDataContent content = new MultipartFormDataContent(); FileStream fileStream = File.OpenRead(toPDF); StreamContent streamContent = new StreamContent(fileStream); streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { // TODO : この辺はサーバの仕様に合わせる Name = "s_file", FileName = Path.GetFileName(toPDF) }; streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/pdf"); content.Add(streamContent); httpRequestMessage.Content = content; Console.WriteLine("<HTTP request Header>-----------------------------------------------------------"); Console.WriteLine(httpRequestMessage.Headers.ToString()); Console.WriteLine("--------------------------------------------------------------------------------"); // HTTPリクエスト送信(非同期) HttpResponseMessage httpResponseMessage = null; try { httpResponseMessage = await httpClient.SendAsync(httpRequestMessage); } catch (Exception exception) { // 通信エラー string message = String.Format("通信エラー : {0}", exception.Message); Console.WriteLine(exception.StackTrace); Console.WriteLine(message); MessageBox.Show(message); return; } finally { streamContent.Dispose(); fileStream.Dispose(); // 中間ファイルを削除 if (File.Exists(toPDF)) { File.Delete(toPDF); } if (File.Exists(toJpeg)) { File.Delete(toJpeg); } } // HTTPステータスチェック if (httpResponseMessage.StatusCode == HttpStatusCode.OK) { // 成功 Console.WriteLine("アップロード成功"); } else { // 失敗 string message = String.Format("アップロードエラー : {0}", httpResponseMessage.ReasonPhrase); Console.WriteLine(message); MessageBox.Show(message); return; } Console.WriteLine("<HTTP request Header>-----------------------------------------------------------"); Console.WriteLine(httpResponseMessage.Headers.ToString()); Console.WriteLine("--------------------------------------------------------------------------------"); } }
public void Dispose_UseMockStreamSourceAndDisposeContent_MockStreamGotDisposed() { var source = new MockStream(new byte[10]); var content = new StreamContent(source); content.Dispose(); Assert.Equal(1, source.DisposeCount); }