public async Task<string> ImageToStream(byte[] image) { try { System.Diagnostics.Debug.WriteLine(image.Length); using (var client = new System.Net.Http.HttpClient()) { using (var content = new System.Net.Http.MultipartFormDataContent()) { content.Add(new System.Net.Http.StreamContent(new MemoryStream(image)), "file", "upload.jpg"); using ( var message = await client.PostAsync("http://bbs.jiangnan.edu.cn/attachments/upload.php", content)) { message.EnsureSuccessStatusCode(); string finalresults = await message.Content.ReadAsStringAsync(); System.Diagnostics.Debug.WriteLine(finalresults); return finalresults; } } } } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e.Message); return e.Message; } }
public static async System.Threading.Tasks.Task UploadImageUser(Context c, Android.Net.Uri imageUri, String Email) { //variable try { //read file into upfilebytes array var upfilebytes = File.ReadAllBytes(Droid.Modules.ImagesHelp.GetPathToImage(c, imageUri)); //create new HttpClient and MultipartFormDataContent and add our file, and StudentId System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(); System.Net.Http.MultipartFormDataContent content = new System.Net.Http.MultipartFormDataContent(); System.Net.Http.ByteArrayContent baContent = new System.Net.Http.ByteArrayContent(upfilebytes); System.Net.Http.StringContent studentIdContent = new System.Net.Http.StringContent(Email); content.Add(baContent, "photod", "avatar.jpg"); content.Add(studentIdContent, "Email"); //upload MultipartFormDataContent content async and store response in response var var response = await client.PostAsync(url1 + "UploadPhotoUser", content); //read response result as a string async into json var var responsestr = response.Content.ReadAsStringAsync().Result; //debug Android.Widget.Toast.MakeText(c, responsestr, Android.Widget.ToastLength.Long).Show(); } catch (Exception e) { //debug Debug.WriteLine("Exception Caught: " + e.ToString()); } }
private async Task <bool> StartSendingAudioMessageAsync(Chat chat, Matbot.Client.Audio audio) { try { using (var httpclient = new System.Net.Http.HttpClient()) { var uri = "https://api.telegram.org/bot" + Token + "/sendAudio?chat_id=" + chat.TelegramId() + "&title=" + audio.Title + "&duration=" + audio.Duration + "&performer=" + audio.Performer; using (var multipartFormDataContent = new System.Net.Http.MultipartFormDataContent()) { var streamContent = new System.Net.Http.StreamContent(audio.AudioStream); streamContent.Headers.Add("Content-Type", "application/octet-stream"); streamContent.Headers.Add("Content-Disposition", "form-data; name=\"audio\"; filename=\"" + audio.Title + ".mp3\""); multipartFormDataContent.Add(streamContent, "file", "" + audio.Title + ".mp3"); using (var message = await httpclient.PostAsync(HttpUtility.UrlPathEncode(uri), multipartFormDataContent)) { var contentString = await message.Content.ReadAsStringAsync(); } } } } catch { return(false); } return(true); }
public static async Task <String> PasteCard(Card c) { var httpclient = new System.Net.Http.HttpClient(); var content = new System.Net.Http.MultipartFormDataContent(); Dictionary <String, String> formData = new Dictionary <String, String>(); content.Add(new System.Net.Http.StringContent(API_KEY), "api_dev_key"); content.Add(new System.Net.Http.StringContent("paste"), "api_option"); content.Add(new System.Net.Http.StringContent(String.Format("Debug data for {0}", c.Name)), "api_paste_name"); content.Add(new System.Net.Http.StringContent(String.Format("Source: {0}\n\n{1}", c.XmlSource, c.XmlData)), "api_paste_code"); var response = await httpclient.PostAsync("http://pastebin.com/api/api_post.php", content); if (!response.IsSuccessStatusCode) { return(null); } return(await response.Content.ReadAsStringAsync()); // var request = System.Net.HttpWebRequest.Create("http://pastebin.com/api/api_post.php"); // request.Method = "POST"; }
public MultipartFormDataContent(System.Net.Http.MultipartFormDataContent containedObject) { if ((containedObject == null)) { throw new System.ArgumentNullException("containedObject"); } this.containedObject = containedObject; }
/// <summary> /// フォームオブジェクトを取得します。 /// </summary> /// <returns></returns> private System.Net.Http.MultipartFormDataContent GetForm() { if (this._form != null) { return(this._form); } this._form = new System.Net.Http.MultipartFormDataContent(); return(this._form); }
public static async Task <RequestResult <OAuthAccessToken> > AccessToken(Api.ClientSecret clientSecrets) { string req_string = string.Format(Strings.oAuthTokenFormat); var requestContent = new System.Net.Http.MultipartFormDataContent { { new System.Net.Http.StringContent(Strings.oAuthTokenRequstValueGrantTypeClientCredentials), Strings.oAuthTokenRequstFieldGrantType } }; return(await Common.RequestAndDeserialize <OAuthAccessToken>(req_string, CacheMode.Uncached, requestContent, authenticatonHeader : clientSecrets)); }
private RequestUploadAuthorization UploadFile(string fileUri, RequestUploadAuthorization requestUploadAuthorization = null) { if (string.IsNullOrEmpty(fileUri)) { throw new ArgumentNullException("FileURI cannot be null", fileUri); } // Get local file path Uri uri = null; string localFilepath = null, contentType = null; if (Uri.TryCreate(fileUri, UriKind.RelativeOrAbsolute, out uri)) { if (uri.Scheme == Uri.UriSchemeFile) { localFilepath = uri.LocalPath; contentType = MimeTypes.MimeTypeMap.GetMimeType(Path.GetExtension(localFilepath)); } else { localFilepath = Path.Combine(Path.GetTempPath(), uri.Segments.Last()); using (WebClient wc = new WebClient()) { wc.DownloadFile(uri, localFilepath); contentType = wc.ResponseHeaders["Content-Type"]; } } } else { throw new ArgumentNullException("Invalid file URI", fileUri); } if (!File.Exists(localFilepath)) { throw new FileNotFoundException("File not found", localFilepath); } // Get the request upload authorization if (requestUploadAuthorization == null) { requestUploadAuthorization = this.GetRequestUploadAuthorization(Path.GetFileName(localFilepath), contentType); } // Create the MultipartFormDataContent var formDataContent = new System.Net.Http.MultipartFormDataContent(); formDataContent.Add(new System.Net.Http.StreamContent(File.OpenRead(localFilepath)), "file", requestUploadAuthorization.Filename); // Post the file var httpClient = new System.Net.Http.HttpClient(); var result = httpClient.PostAsync(requestUploadAuthorization.UploadURL, formDataContent); if (result.Result.StatusCode != System.Net.HttpStatusCode.NoContent) { throw result.Exception ?? new Exception(string.Format("Code {0} : {1}", (int)result.Result.StatusCode, result.Result.ReasonPhrase)); } return(requestUploadAuthorization); }
private async Task OnUploadAsync() { var file = await CrossMedia.Current.PickVideoAsync(); using (var fs = file.GetStream()) { System.Net.Http.MultipartFormDataContent mfd = new System.Net.Http.MultipartFormDataContent(); var content = new System.Net.Http.StreamContent(fs); mfd.Add(content, "file1", System.IO.Path.GetFileName(file.Path)); await XamarinFileUploader.FileUploaderService.Instance.StartUpload("1", "https://secure.800casting.com/upload/uploadtemp", "POST", mfd); } }
public static async Task<String> PasteCard(Card c) { var httpclient = new System.Net.Http.HttpClient(); var content = new System.Net.Http.MultipartFormDataContent(); Dictionary<String, String> formData = new Dictionary<String, String>(); content.Add(new System.Net.Http.StringContent(API_KEY), "api_dev_key"); content.Add(new System.Net.Http.StringContent("paste"), "api_option"); content.Add(new System.Net.Http.StringContent(String.Format("Debug data for {0}", c.Name)), "api_paste_name"); content.Add(new System.Net.Http.StringContent(String.Format("Source: {0}\n\n{1}", c.XmlSource, c.XmlData)), "api_paste_code"); var response = await httpclient.PostAsync("http://pastebin.com/api/api_post.php", content); if (!response.IsSuccessStatusCode) return null; return await response.Content.ReadAsStringAsync(); // var request = System.Net.HttpWebRequest.Create("http://pastebin.com/api/api_post.php"); // request.Method = "POST"; }
public static void SendToApi() { string[] uploadfiles = new string[] { "D:\\2d.jpg", "d:\\140317.ajk" }; //上传文件路径 string url = "http://localhost:49840//api/fileapi"; //服务地址 using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient()) { using (var content = new System.Net.Http.MultipartFormDataContent())//表明是通过multipart/form-data的方式上传数据 { //循环添加文件至列表 foreach (var path in uploadfiles) { var fileContent = new System.Net.Http.ByteArrayContent(System.IO.File.ReadAllBytes(path)); fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = System.IO.Path.GetFileName(path),//此处可以自定义文件名 }; content.Add(fileContent); } var result = client.PostAsync(url, content).Result;//提交post请求 } } }
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <summary>上传附件</summary> /// <param name="saId">景点id</param> /// <param name="craId">附件id</param> /// <param name="uploadType">上传类型 /// 0:常规文件 /// 1:视频封面</param> /// <param name="attaType">附件类型(0:图片,1:视频)</param> /// <param name="file">文件</param> /// <exception cref="ApiException">A server side error occurred.</exception> public async System.Threading.Tasks.Task <Tourism.STD.Models.InfoModel <Tourism.STD.Models.Content.TempFileInfoForContent> > UploadTempFileForContentAsync(string saId, string craId, int?uploadType, int?attaType, FileParameter file, System.Threading.CancellationToken cancellationToken) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append("Api/Content/UploadTempFileForContent"); var client_ = _httpClient; var disposeClient_ = false; try { using (var request_ = await CreateHttpRequestMessageAsync(cancellationToken).ConfigureAwait(false)) { var boundary_ = System.Guid.NewGuid().ToString(); var content_ = new System.Net.Http.MultipartFormDataContent(boundary_); content_.Headers.Remove("Content-Type"); content_.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary_); if (saId != null) { content_.Add(new System.Net.Http.StringContent(ConvertToString(saId, System.Globalization.CultureInfo.InvariantCulture)), "saId"); } if (craId != null) { content_.Add(new System.Net.Http.StringContent(ConvertToString(craId, System.Globalization.CultureInfo.InvariantCulture)), "craId"); } if (uploadType == null) { throw new System.ArgumentNullException("uploadType"); } else { content_.Add(new System.Net.Http.StringContent(ConvertToString(uploadType, System.Globalization.CultureInfo.InvariantCulture)), "uploadType"); } if (attaType == null) { throw new System.ArgumentNullException("attaType"); } else { content_.Add(new System.Net.Http.StringContent(ConvertToString(attaType, System.Globalization.CultureInfo.InvariantCulture)), "attaType"); } if (file != null) { var content_file_ = new System.Net.Http.StreamContent(file.Data); if (!string.IsNullOrEmpty(file.ContentType)) { content_file_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(file.ContentType); } content_.Add(content_file_, "file", file.FileName ?? "file"); } request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); var disposeResponse_ = true; try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) { headers_[item_.Key] = item_.Value; } } ProcessResponse(client_, response_); var status_ = (int)response_.StatusCode; if (status_ == 200) { var objectResponse_ = await ReadObjectResponseAsync <Tourism.STD.Models.InfoModel <Tourism.STD.Models.Content.TempFileInfoForContent> >(response_, headers_).ConfigureAwait(false); return(objectResponse_.Object); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally { if (disposeResponse_) { response_.Dispose(); } } } } finally { if (disposeClient_) { client_.Dispose(); } } }
/// <returns>Success</returns> /// <exception cref="SwaggerException">A server side error occurred.</exception> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> public async System.Threading.Tasks.Task <string> DownloadJobFileResultAsync(string filename, string jobId, System.Threading.CancellationToken cancellationToken, string fileToWriteTo) { string outputFile = ""; var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/DownloadJobFileResult"); var client_ = _httpClient; try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { var boundary_ = System.Guid.NewGuid().ToString(); var content_ = new System.Net.Http.MultipartFormDataContent(boundary_); content_.Headers.Remove("Content-Type"); content_.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary_); if (filename != null) { content_.Add(new System.Net.Http.StringContent(ConvertToString(filename, System.Globalization.CultureInfo.InvariantCulture)), "filename"); } if (jobId != null) { content_.Add(new System.Net.Http.StringContent(ConvertToString(jobId, System.Globalization.CultureInfo.InvariantCulture)), "jobId"); } request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/octet-stream")); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) { headers_[item_.Key] = item_.Value; } } ProcessResponse(client_, response_); using (System.IO.Stream streamToReadFrom = await response_.Content.ReadAsStreamAsync()) { outputFile = response_.Content.Headers.ContentDisposition.FileName; using (Stream streamToWriteTo = File.Open(Path.Combine(fileToWriteTo, outputFile), FileMode.Create)) { await streamToReadFrom.CopyToAsync(streamToWriteTo); } } var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "200" || status_ == "206") { var responseStream_ = response_.Content == null ? System.IO.Stream.Null : await response_.Content.ReadAsStreamAsync().ConfigureAwait(false); var fileResponse_ = new FileResponse((int)response_.StatusCode, headers_, responseStream_, null, response_); client_ = null; response_ = null; // response and client are disposed by FileResponse return(outputFile); } else if (status_ != "200" && status_ != "204") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null); } } finally { if (response_ != null) { response_.Dispose(); } } } } finally { } return(outputFile); }
/// <returns>Success</returns> /// <exception cref="SwaggerException">A server side error occurred.</exception> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> public async System.Threading.Tasks.Task <DocProof> PutProofDocAsync(FileParameter proofDoc, string bindingId, string citizenIdentifier, System.Threading.CancellationToken cancellationToken) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/DocProof/PutProofDocs?"); if (bindingId != null) { urlBuilder_.Append("bindingId=").Append(System.Uri.EscapeDataString(ConvertToString(bindingId, System.Globalization.CultureInfo.InvariantCulture))).Append("&"); } if (citizenIdentifier != null) { urlBuilder_.Append("citizenIdentifier=").Append(System.Uri.EscapeDataString(ConvertToString(citizenIdentifier, System.Globalization.CultureInfo.InvariantCulture))).Append("&"); } urlBuilder_.Length--; var client_ = _httpClient; try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { var boundary_ = System.Guid.NewGuid().ToString(); var content_ = new System.Net.Http.MultipartFormDataContent(boundary_); content_.Headers.Remove("Content-Type"); content_.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary_); if (proofDoc != null) { var content_proofDoc_ = new System.Net.Http.StreamContent(proofDoc.Data); if (!string.IsNullOrEmpty(proofDoc.ContentType)) { content_proofDoc_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(proofDoc.ContentType); } content_.Add(content_proofDoc_, "proofDoc", proofDoc.FileName ?? "proofDoc"); } request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) { headers_[item_.Key] = item_.Value; } } ProcessResponse(client_, response_); var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "200") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); var result_ = default(DocProof); try { result_ = Newtonsoft.Json.JsonConvert.DeserializeObject <DocProof>(responseData_, _settings.Value); return(result_); } catch (System.Exception exception_) { throw new SwaggerException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_); } } else if (status_ != "200" && status_ != "204") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null); } return(default(DocProof)); } finally { if (response_ != null) { response_.Dispose(); } } } } finally { } }
public async Task <bool> SetImage(string url, Image img) { if (url == null || url.Length == 0) { throw new System.ArgumentNullException("Url"); } if (!url.StartsWith("/")) { url = "/" + url; } var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl).Append(url); var client_ = new System.Net.Http.HttpClient(); try { byte[] imageToSend = null; if (img != null) { using (var memoryStream = new System.IO.MemoryStream()) { try { img.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg); } catch { Bitmap bitmap = (Bitmap)img; bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg); } imageToSend = memoryStream.ToArray(); } } using (var request_ = new System.Net.Http.HttpRequestMessage()) { System.Net.Http.HttpContent content = new System.Net.Http.ByteArrayContent(imageToSend); content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/png"); var content_ = new System.Net.Http.MultipartFormDataContent(); content_.Add(content); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("PUT"); request_.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded")); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false); try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); foreach (var item_ in response_.Content.Headers) { headers_[item_.Key] = item_.Value; } ProcessResponse(client_, response_); var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "200") { return(true); } else if (status_ == "304") { return(true); } else { if (status_ != "200" && status_ != "204") { return(false); } } return(false); } finally { if (response_ != null) { response_.Dispose(); } } } } finally { if (client_ != null) { client_.Dispose(); } } }
public async System.Threading.Tasks.Task <System.Text.Json.JsonElement> SendFilesAsync(System.Collections.Generic.Dictionary <System.String, System.Collections.Generic.List <SoftmakeAll.SDK.Communication.REST.File> > FormData) { if (System.String.IsNullOrWhiteSpace(this.URL)) { throw new System.Exception(SoftmakeAll.SDK.Communication.REST.EmptyURLErrorMessage); } this.HasRequestErrors = false; using (System.Net.Http.HttpClient HttpClient = new System.Net.Http.HttpClient()) { if (this.Headers.Count > 0) { foreach (System.Collections.Generic.KeyValuePair <System.String, System.String> Header in this.Headers) { HttpClient.DefaultRequestHeaders.Add(Header.Key, Header.Value); } } this.AddAuthorizationHeader(HttpClient); using (System.Net.Http.MultipartFormDataContent MultipartFormDataContent = new System.Net.Http.MultipartFormDataContent()) { if ((FormData != null) && (FormData.Count > 0)) { foreach (System.Collections.Generic.KeyValuePair <System.String, System.Collections.Generic.List <SoftmakeAll.SDK.Communication.REST.File> > Item in FormData) { if ((!(System.String.IsNullOrWhiteSpace(Item.Key))) && (Item.Value != null) && (Item.Value.Any())) { foreach (SoftmakeAll.SDK.Communication.REST.File File in Item.Value) { System.Net.Http.ByteArrayContent ByteArrayContent = new System.Net.Http.ByteArrayContent(File.Contents); if (!(System.String.IsNullOrWhiteSpace(File.ContentType))) { ByteArrayContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(File.ContentType); } MultipartFormDataContent.Add(ByteArrayContent, Item.Key, File.Name); } } } } if (this.Timeout > 0) { HttpClient.Timeout = System.TimeSpan.FromMilliseconds(this.Timeout); } try { System.Net.Http.HttpResponseMessage HttpResponseMessage; switch (this.Method) { case "PATCH": { HttpResponseMessage = await HttpClient.PatchAsync(this.URL, MultipartFormDataContent); break; } case "POST": { HttpResponseMessage = await HttpClient.PostAsync(this.URL, MultipartFormDataContent); break; } case "PUT": { HttpResponseMessage = await HttpClient.PutAsync(this.URL, MultipartFormDataContent); break; } default: throw new System.NotSupportedException($"Method {this.Method} is not supported for sending files. Plese use PATCH, POST or PUT."); } this._StatusCode = HttpResponseMessage.StatusCode; this.HasRequestErrors = false; System.Byte[] APIResult = await HttpResponseMessage.Content.ReadAsByteArrayAsync(); if (APIResult == null) { return(new System.Text.Json.JsonElement()); } return(System.Text.Encoding.UTF8.GetString(APIResult).ToJsonElement()); } catch (System.Exception ex) { this.HasRequestErrors = ex.InnerException == null; this._StatusCode = System.Net.HttpStatusCode.InternalServerError; return(new System.Text.Json.JsonElement()); } } } }
async public ValueTask <ActionResult> TorrentUpload() { // Копируем torrent MemoryStream mem = new MemoryStream(); await HttpContext.Request.Form.Files[0].CopyToAsync(mem); var torrent = mem.ToArray(); if (torrent == null || torrent.Length == 0) { return(Json(new { code = 1 })); } // Получаем хост var ports = CronController.currenthost.ports; string thost = $"{HttpContext.Request.Host.Value}:{ports[random.Next(0, ports.Length)]}"; string resupload = null; // Отправляем торрент на сервер using (var httpClient = new System.Net.Http.HttpClient()) { var form = new System.Net.Http.MultipartFormDataContent(); form.Add(new System.Net.Http.ByteArrayContent(torrent, 0, torrent.Length), "file1", "filename"); form.Add(new System.Net.Http.StringContent(""), "title"); form.Add(new System.Net.Http.StringContent(""), "poster"); form.Add(new System.Net.Http.StringContent(""), "data"); var response = await httpClient.PostAsync($"http://{thost}/torrent/upload", form); resupload = await response.Content.ReadAsStringAsync(); if (string.IsNullOrWhiteSpace(resupload)) { return(Json(new { code = 2 })); } string hash = Regex.Match(resupload, "\"hash\":\"([^\"]+)\"").Groups[1].Value; if (string.IsNullOrWhiteSpace(hash)) { return(Json(new { code = 3 })); } #region Сохраняем в базу if (HttpContext.Request.Form.TryGetValue("save", out var _save) && _save.ToString() == "true") { string userid = getUserId(); if (!torDb.TryGetValue(userid, out List <TorInfo> infos)) { torDb[userid] = new List <TorInfo>(); } infos = torDb[userid]; var item = infos.FirstOrDefault(i => i.hash == hash); var tinfo = new TorInfo() { title = Regex.Match(resupload, "\"name\":\"([^\"]+)\"").Groups[1].Value.Split(".")[0], poster = Regex.Match(resupload, "\"poster\":\"([^\"]+)\"").Groups[1].Value, hash = hash }; if (item != null) { item.title = tinfo.title; item.poster = tinfo.poster; } else { infos.Insert(0, tinfo); } torDb[userid] = infos; } #endregion // Сохраняем кеш хоста memoryCache.Set($"tplay:torrents:{HttpContext.Connection.RemoteIpAddress}:{hash}", thost, DateTime.Today.AddHours(4)); } // Отдаем json return(Content(Regex.Replace(resupload, "(^\\[|\\]$)", ""), "application/json")); }
/// <param name="file">file chunk</param> /// <param name="json">json data</param> /// <exception cref="SwaggerException">A server side error occurred.</exception> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> public async System.Threading.Tasks.Task <FileResponse> UploadAsync(FileParameter file, string json, System.Threading.CancellationToken cancellationToken) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/Upload/Upload"); var client_ = _httpClient; try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { var boundary_ = System.Guid.NewGuid().ToString(); var content_ = new System.Net.Http.MultipartFormDataContent(boundary_); content_.Headers.Remove("Content-Type"); content_.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary_); if (file == null) { throw new System.ArgumentNullException("file"); } else { var content_file_ = new System.Net.Http.StreamContent(file.Data); if (!string.IsNullOrEmpty(file.ContentType)) { content_file_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(file.ContentType); } content_.Add(content_file_, "file", file.FileName ?? "file"); } if (json == null) { throw new System.ArgumentNullException("json"); } else { content_.Add(new System.Net.Http.StringContent(ConvertToString(json, System.Globalization.CultureInfo.InvariantCulture)), "json"); } request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/octet-stream")); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) { headers_[item_.Key] = item_.Value; } } ProcessResponse(client_, response_); var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "200" || status_ == "206") { var responseStream_ = response_.Content == null ? System.IO.Stream.Null : await response_.Content.ReadAsStreamAsync().ConfigureAwait(false); var fileResponse_ = new FileResponse((int)response_.StatusCode, headers_, responseStream_, null, response_); client_ = null; response_ = null; // response and client are disposed by FileResponse return(fileResponse_); } else if (status_ != "200" && status_ != "204") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null); } return(default(FileResponse)); } finally { if (response_ != null) { response_.Dispose(); } } } } finally { } }
/// <returns>Success</returns> /// <exception cref="SwaggerException">A server side error occurred.</exception> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> public async System.Threading.Tasks.Task <JobResult> UploadJobAsync(FileParameter file, string fScriptParams, string scriptFilename, string outputFileFormat, System.Threading.CancellationToken cancellationToken) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/UploadJob"); var client_ = _httpClient; try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { var boundary_ = System.Guid.NewGuid().ToString(); var content_ = new System.Net.Http.MultipartFormDataContent(boundary_); content_.Headers.Remove("Content-Type"); content_.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary_); if (file != null) { var content_file_ = new System.Net.Http.StreamContent(file.Data); if (!string.IsNullOrEmpty(file.ContentType)) { content_file_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(file.ContentType); } content_.Add(content_file_, "file", file.FileName ?? "file"); } if (fScriptParams != null) { content_.Add(new System.Net.Http.StringContent(ConvertToString(fScriptParams, System.Globalization.CultureInfo.InvariantCulture)), "fScriptParams"); } if (scriptFilename != null) { content_.Add(new System.Net.Http.StringContent(ConvertToString(scriptFilename, System.Globalization.CultureInfo.InvariantCulture)), "scriptFilename"); } if (outputFileFormat != null) { content_.Add(new System.Net.Http.StringContent(ConvertToString(outputFileFormat, System.Globalization.CultureInfo.InvariantCulture)), "outputFileFormat"); } request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) { headers_[item_.Key] = item_.Value; } } ProcessResponse(client_, response_); var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "200") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); var result_ = default(JobResult); try { result_ = Newtonsoft.Json.JsonConvert.DeserializeObject <JobResult>(responseData_, _settings.Value); return(result_); } catch (System.Exception exception_) { throw new SwaggerException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_); } } else if (status_ != "200" && status_ != "204") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null); } return(default(JobResult)); } finally { if (response_ != null) { response_.Dispose(); } } } } finally { } }
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <exception cref="GeoClientException">A server side error occurred.</exception> public async System.Threading.Tasks.Task<bool> UploadFileAsync(FileParameter file, System.Threading.CancellationToken cancellationToken) { var url_ = string.Format("{0}/{1}", BaseUrl, "api/Geo/UploadFile"); using (var client_ = await CreateHttpClientAsync(cancellationToken).ConfigureAwait(false)) { var request_ = await CreateHttpRequestMessageAsync(cancellationToken).ConfigureAwait(false); PrepareRequest(client_, ref url_); var content_ = new System.Net.Http.MultipartFormDataContent(); if (file != null) content_.Add(new System.Net.Http.StreamContent(file.Data), "file", file.FileName ?? "file"); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseContentRead, cancellationToken).ConfigureAwait(false); ProcessResponse(client_, response_); var responseData_ = await response_.Content.ReadAsByteArrayAsync().ConfigureAwait(false); var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "200") { var result_ = default(bool); try { if (responseData_.Length > 0) result_ = Newtonsoft.Json.JsonConvert.DeserializeObject<bool>(System.Text.Encoding.UTF8.GetString(responseData_, 0, responseData_.Length), new Newtonsoft.Json.JsonConverter[] { new Newtonsoft.Json.Converters.StringEnumConverter(), new JsonExceptionConverter() }); return result_; } catch (System.Exception exception) { throw new GeoClientException("Could not deserialize the response body.", status_, responseData_, exception); } } else if (status_ != "200" && status_ != "204") throw new GeoClientException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", status_, responseData_, null); return default(bool); } }
/// <summary> /// Upload file /// </summary> /// <param name='fileContent'> /// File to upload. /// </param> /// <param name='fileName'> /// File name to upload. Name has to be spelled exactly as written here. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task <Microsoft.Rest.HttpOperationResponse <System.IO.Stream> > UploadFileWithHttpMessagesAsync(System.IO.Stream fileContent, string fileName, System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (fileContent == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "fileContent"); } if (fileName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "fileName"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary <string, object> tracingParameters = new System.Collections.Generic.Dictionary <string, object>(); tracingParameters.Add("fileContent", fileContent); tracingParameters.Add("fileName", fileName); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "UploadFile", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "formdata/stream/uploadfile").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; System.Net.Http.MultipartFormDataContent _multiPartContent = new System.Net.Http.MultipartFormDataContent(); if (fileContent != null) { System.Net.Http.StreamContent _fileContent = new System.Net.Http.StreamContent(fileContent); _fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream"); System.IO.FileStream _fileContentAsFileStream = fileContent as System.IO.FileStream; if (_fileContentAsFileStream != null) { System.Net.Http.Headers.ContentDispositionHeaderValue _contentDispositionHeaderValue = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data"); _contentDispositionHeaderValue.Name = "fileContent"; _contentDispositionHeaderValue.FileName = _fileContentAsFileStream.Name; _fileContent.Headers.ContentDisposition = _contentDispositionHeaderValue; } _multiPartContent.Add(_fileContent, "fileContent"); } if (fileName != null) { System.Net.Http.StringContent _fileName = new System.Net.Http.StringContent(fileName, System.Text.Encoding.UTF8); _multiPartContent.Add(_fileName, "fileName"); } _httpRequest.Content = _multiPartContent; // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse <System.IO.Stream>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _result.Body = await _httpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
private static async System.Threading.Tasks.Task PostAsync(ServiceResponse response, Uri uri, List <Tuple <string, string> > UriSubstitutes, List <Tuple <string, string> > headers, List <Tuple <string, string> > postDataSubstitutes, string text, System.Collections.Generic.Dictionary <string, string> apiArgs, int maxResponseLength = 10000000) { Settings.Request request = response.Request; bool binaryResponse = request.response.type == "binary"; if (uri == null) { uri = MakeUri(request, apiArgs, UriSubstitutes, text); } if (headers == null) { headers = MakeHeaders(request); } List <string> data = MakePostDataSubstitutes(request, text, null, apiArgs, postDataSubstitutes); if (data.Count == 1 && !isMultipart(headers)) { await MakePostCurl(uri, headers, data, request == null?null : request.response.jq, binaryResponse); System.Net.Http.HttpContent requestContent = new System.Net.Http.StringContent(data[0]); await SystemNetAsync(response, "POST", uri, headers, requestContent, binaryResponse, maxResponseLength); response.FileName = "curl-" + httpCallCount; return; } else { #if true // MicrosoftCognitiveInsightService can use multipart? See Post Byte[] overload above for helpful details. throw new Exception("PostAsync: multipart/form-data not implemented. Doesn't seem to work with System.Net.Http"); #else List <KeyValuePair <string, string> > kvps = new List <KeyValuePair <string, string> >(); foreach (string s in data) { kvps.Add(new KeyValuePair <string, string>(s.Substring(0, s.IndexOf("=")), s.Substring(s.IndexOf("=") + 1))); } await MakePostMultiPartCurl(uri, headers, kvps, request.response.jq, binaryResponse); List <KeyValuePair <string, string> > newkvps = new List <KeyValuePair <string, string> >(); foreach (KeyValuePair <string, string> kvp in kvps) { string s = kvp.Value; if (kvp.Value[0] == '@') { byte[] bytes = System.IO.File.ReadAllBytes(kvp.Value.Substring(1)); s = Convert.ToBase64String(bytes); } newkvps.Add(new KeyValuePair <string, string>(kvp.Key, s)); } System.Net.Http.MultipartFormDataContent multiPartRequestContent = new System.Net.Http.MultipartFormDataContent(); multiPartRequestContent.Add(new System.Net.Http.FormUrlEncodedContent(newkvps)); await SystemNetAsync(response, "POST", uri, headers, multiPartRequestContent, binaryResponse, maxResponseLength); response.FileName = "curl-" + httpCallCount; #endif } #if WINDOWS_UWP // major bit rot. Multi-part not implemented. if (Options.options.Services.APIs.PreferSystemNet) { response = await SystemNetAsync("POST", uri, headers, new System.Net.Http.ByteArrayContent(requestContent), binaryResponse, maxResponseLength); } else { response = await WindowsWebAsync("POST", new Uri(requestUri), audioBytes, sampleRate, contentType, headerValue); } #else { response = await SystemNetAsync("POST", uri, headers, requestContent, binaryResponse, maxResponseLength); } response.FileName = "curl-" + httpCallCount; return(response); #endif }
private static async System.Threading.Tasks.Task PostAsync(ServiceResponse response, Uri uri, List <Tuple <string, string> > UriSubstitutes, List <Tuple <string, string> > headers, List <Tuple <string, string> > postDataSubstitutes, byte[] bytes, System.Collections.Generic.Dictionary <string, string> apiArgs, int maxResponseLength = 10000000) { Settings.Request request = response.Request; bool binaryResponse = request.response.type == "binary"; string fileName = null; if (apiArgs.ContainsKey("fileName")) { fileName = apiArgs["fileName"]; } if (uri == null) { uri = MakeUri(request, apiArgs, UriSubstitutes); } if (headers == null) { headers = MakeHeaders(request); } List <string> texts = MakePostDataSubstitutes(request, null, bytes, apiArgs, postDataSubstitutes); System.Net.Http.HttpContent requestContent; if (texts == null) { await MakePostCurl(uri, headers, bytes, request.response.jq, binaryResponse); requestContent = new System.Net.Http.ByteArrayContent(bytes); } else { if (texts.Count == 1 && !isMultipart(headers)) { await MakePostCurl(uri, headers, texts, request.response.jq, binaryResponse); if (texts[0] == null) // Houndify text intent { requestContent = new System.Net.Http.ByteArrayContent(bytes); } else { requestContent = new System.Net.Http.StringContent(texts[0]); } await SystemNetAsync(response, "POST", uri, headers, requestContent, binaryResponse, maxResponseLength); return; } else { List <KeyValuePair <string, string> > lkvp = new List <KeyValuePair <string, string> >(); foreach (string s in texts) { lkvp.Add(new KeyValuePair <string, string>(s.Substring(0, s.IndexOf("=")), s.Substring(s.IndexOf("=") + 1))); } await MakePostMultiPartCurl(uri, headers, lkvp, request.response.jq, binaryResponse); System.Net.Http.MultipartFormDataContent multiPartRequestContent = new System.Net.Http.MultipartFormDataContent(); foreach (KeyValuePair <string, string> kvp in lkvp) { System.Net.Http.HttpContent ht; switch (kvp.Key) { case "file": ht = new System.Net.Http.ByteArrayContent(bytes); ht.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream"); // optional for HPE Haven? multiPartRequestContent.Add(ht, "\"file\"", "\"" + fileName + "\""); break; default: ht = new System.Net.Http.StringContent(kvp.Value); ht.Headers.ContentType = null; multiPartRequestContent.Add(ht, '"' + kvp.Key + '"'); break; } } await SystemNetAsync(response, "POST", uri, headers, multiPartRequestContent, binaryResponse, maxResponseLength); response.FileName = "curl-" + httpCallCount; return; } } #if WINDOWS_UWP if (Options.options.Services.APIs.PreferSystemNet) { await SystemNetAsync("POST", uri, headers, new System.Net.Http.ByteArrayContent(requestContent), binaryResponse, maxResponseLength); } else { await WindowsWebAsync("POST", new Uri(requestUri), audioBytes, sampleRate, contentType, headerValue); } #else await SystemNetAsync(response, "POST", uri, headers, requestContent, binaryResponse, maxResponseLength); #endif response.FileName = "curl-" + httpCallCount; }
/// <summary> /// Runs the queued task /// </summary> /// <param name="e">The task to run</param> /// <returns>An awaitable task</returns> private async Task RunTaskAsync(QueueEntry e) { // Start the task var t = await this.RunInTransactionAsync(db => { // Mark the task itself as running var now = DateTime.Now; e.LastTried = now; e.Status = QueueEntryStatus.Running; db.Update <QueueEntry>(new { e.LastTried, e.Status }, x => x.ID == e.ID); // Create a runner entry return(db.InsertItem <QueueRunLog>( new QueueRunLog() { QueueName = Name, TaskID = e.ID, Method = e.Method, Url = e.Url, ContentType = e.ContentType, Started = now } )); }); using (var c = new System.Net.Http.HttpClient()) using (var rq = new System.Net.Http.HttpRequestMessage()) try { rq.Method = new System.Net.Http.HttpMethod(e.Method); var isSelfRequest = e.Url.StartsWith("/"); var targeturl = e.Url; if (isSelfRequest) { targeturl = this.SelfUrl + targeturl; } rq.RequestUri = new Uri(targeturl); if (!string.IsNullOrWhiteSpace(e.Headers)) { var headers = Newtonsoft.Json.JsonConvert.DeserializeObject <Dictionary <string, string> >(e.Headers); foreach (var h in headers) { rq.Headers.Remove(h.Key); rq.Headers.Add(h.Key, h.Value); } } if (isSelfRequest) { rq.Headers.Remove(SecureHeaderName); rq.Headers.Add(SecureHeaderName, SecureHeaderValue); } switch (e.ContentType) { case "multipart/form-data": var mp = new System.Net.Http.MultipartFormDataContent(); foreach (var item in Newtonsoft.Json.JsonConvert.DeserializeObject <Dictionary <string, string> >(e.Payload)) { mp.Add(new System.Net.Http.StringContent(item.Value), item.Key); } rq.Content = mp; break; case "application/x-www-form-urlencoded": case "application/json": case "text/plan": case "text/html": rq.Content = new System.Net.Http.StringContent(e.Payload, System.Text.Encoding.UTF8, e.ContentType); break; case "application/octet-stream": rq.Content = new System.Net.Http.ByteArrayContent(Convert.FromBase64String(e.Payload)); break; default: throw new ArgumentException($"Cannot send request with content type: {e.ContentType}"); } using (var resp = await c.SendAsync(rq, m_cancelSource.Token)) { t.Finished = DateTime.Now; t.StatusCode = (int)resp.StatusCode; t.StatusMessage = resp.ReasonPhrase; t.Result = await resp.Content.ReadAsStringAsync(); resp.EnsureSuccessStatusCode(); await this.RunInTransactionAsync(db => db.UpdateItem(t)); } } catch (Exception ex) { t.Result = string.Join( Environment.NewLine, new string[] { t.Result, "Exception: " + ex.ToString() }.Where(x => !string.IsNullOrWhiteSpace(x)) ); throw; } finally { t.Finished = DateTime.Now; await this.RunInTransactionAsync(db => db.UpdateItem(t)); // Make sure the runner picks up on out results // But make sure the runner task has finished before we signal Task.Delay(TimeSpan.FromMilliseconds(500)).ContinueWith(_ => SignalRunner()); } }
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <exception cref="GeoClientException">A server side error occurred.</exception> public async System.Threading.Tasks.Task UploadFilesAsync(System.Collections.Generic.IEnumerable<FileParameter> files, System.Threading.CancellationToken cancellationToken) { var url_ = string.Format("{0}/{1}", BaseUrl, "api/Geo/UploadFiles"); using (var client_ = await CreateHttpClientAsync(cancellationToken).ConfigureAwait(false)) { var request_ = await CreateHttpRequestMessageAsync(cancellationToken).ConfigureAwait(false); PrepareRequest(client_, ref url_); var content_ = new System.Net.Http.MultipartFormDataContent(); if (files != null) foreach(var item_ in files) { content_.Add(new System.Net.Http.StreamContent(item_.Data), "files", item_.FileName ?? "files"); } request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseContentRead, cancellationToken).ConfigureAwait(false); ProcessResponse(client_, response_); var responseData_ = await response_.Content.ReadAsByteArrayAsync().ConfigureAwait(false); var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "204") { return; } else if (status_ != "200" && status_ != "204") throw new GeoClientException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", status_, responseData_, null); } }
/// <summary> /// 現在のセッションをクローズします。 /// </summary> private void Close() { this._client = null; this._form = null; }
public static async System.Threading.Tasks.Task UploadImageCompany(Context c, Android.Net.Uri logo, Android.Net.Uri stand, Android.Net.Uri photo1, Android.Net.Uri photo2, Android.Net.Uri photo3, Android.Net.Uri photo4, Android.Net.Uri photo5, String Email) { //variable try { System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(); System.Net.Http.MultipartFormDataContent content = new System.Net.Http.MultipartFormDataContent(); //read file into upfilebytes array if (logo != null) { var ilogo = File.ReadAllBytes(Droid.Modules.ImagesHelp.GetPathToImage(c, logo)); System.Net.Http.ByteArrayContent clogo = new System.Net.Http.ByteArrayContent(ilogo); content.Add(clogo, "logo", "logo.jpg"); } if (stand != null) { var istand = File.ReadAllBytes(Droid.Modules.ImagesHelp.GetPathToImage(c, stand)); System.Net.Http.ByteArrayContent cstand = new System.Net.Http.ByteArrayContent(istand); content.Add(cstand, "stand", "stand.jpg"); } if (photo1 != null) { var iphoto1 = File.ReadAllBytes(Droid.Modules.ImagesHelp.GetPathToImage(c, photo1)); System.Net.Http.ByteArrayContent cphoto1 = new System.Net.Http.ByteArrayContent(iphoto1); content.Add(cphoto1, "photo1", "p1.jpg"); } if (photo2 != null) { var iphoto2 = File.ReadAllBytes(Droid.Modules.ImagesHelp.GetPathToImage(c, photo2)); System.Net.Http.ByteArrayContent cphoto2 = new System.Net.Http.ByteArrayContent(iphoto2); content.Add(cphoto2, "photo2", "p2.jpg"); } if (photo3 != null) { var iphoto3 = File.ReadAllBytes(Droid.Modules.ImagesHelp.GetPathToImage(c, photo3)); System.Net.Http.ByteArrayContent cphoto3 = new System.Net.Http.ByteArrayContent(iphoto3); content.Add(cphoto3, "photo3", "p3.jpg"); } if (photo4 != null) { var iphoto4 = File.ReadAllBytes(Droid.Modules.ImagesHelp.GetPathToImage(c, photo4)); System.Net.Http.ByteArrayContent cphoto4 = new System.Net.Http.ByteArrayContent(iphoto4); content.Add(cphoto4, "photo4", "p4.jpg"); } if (photo5 != null) { var iphoto5 = File.ReadAllBytes(Droid.Modules.ImagesHelp.GetPathToImage(c, photo5)); System.Net.Http.ByteArrayContent cphoto5 = new System.Net.Http.ByteArrayContent(iphoto5); content.Add(cphoto5, "photo5", "p5.jpg"); } //create new HttpClient and MultipartFormDataContent and add our file, and StudentId System.Net.Http.StringContent studentIdContent = new System.Net.Http.StringContent(Email); content.Add(studentIdContent, "Email"); //upload MultipartFormDataContent content async and store response in response var var response = await client.PostAsync(url + "UploadPhotoCompany", content); //read response result as a string async into json var var responsestr = response.Content.ReadAsStringAsync().Result; //debug Android.Widget.Toast.MakeText(c, responsestr, Android.Widget.ToastLength.Long).Show(); } catch (Exception e) { //debug Debug.WriteLine("Exception Caught: " + e.ToString()); } }
/// <summary>Updates a pet in the store with form data</summary> /// <param name="petId">ID of pet that needs to be updated</param> /// <param name="name">Updated name of the pet</param> /// <param name="status">Updated status of the pet</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <exception cref="SwaggerException">A server side error occurred.</exception> public async System.Threading.Tasks.Task UpdatePetWithFormAsync(int petId, string name, string status, System.Threading.CancellationToken cancellationToken) { var url_ = string.Format("{0}/{1}", BaseUrl, "pet/{petId}"); if (petId == null) throw new System.ArgumentNullException("petId"); url_ = url_.Replace("{petId}", System.Uri.EscapeDataString(petId.ToString())); using (var client_ = new System.Net.Http.HttpClient()) { var request_ = new System.Net.Http.HttpRequestMessage(); PrepareRequest(client_, ref url_); var content_ = new System.Net.Http.MultipartFormDataContent(); if (name != null) content_.Add(new System.Net.Http.StringContent(name.ToString()), "name"); if (status != null) content_.Add(new System.Net.Http.StringContent(status.ToString()), "status"); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseContentRead, cancellationToken).ConfigureAwait(false); ProcessResponse(client_, response_); var responseData_ = await response_.Content.ReadAsByteArrayAsync().ConfigureAwait(false); var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "405") { throw new SwaggerException("Invalid input", status_, responseData_, null); } else if (status_ != "200" && status_ != "204") throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", status_, responseData_, null); } }
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <summary>上传任务拍照临时文件</summary> /// <exception cref="ApiException">A server side error occurred.</exception> /// <param name="file"></param> public async System.Threading.Tasks.Task <Tourism.STD.Models.InfoModel <NetCore.TempFileInfo> > UploadForTaskTempFileForProgressAsync(FileParameter file, System.Threading.CancellationToken cancellationToken) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append("PhoneApi/SceniceMap/UploadForTaskTempFile"); var client_ = _httpClient; var disposeClient_ = false; try { using (var request_ = await CreateHttpRequestMessageAsync(cancellationToken).ConfigureAwait(false)) { var boundary_ = System.Guid.NewGuid().ToString(); var content_ = new System.Net.Http.MultipartFormDataContent(boundary_); content_.Headers.Remove("Content-Type"); content_.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary_); if (file != null) { var content_file_ = new ProgressContent(file.Data, CacheBufferLengthForProgress); var methonInfo = MethodBase.GetCurrentMethod(); content_file_.Progress += (arg, arg1) => { InvokeProgressEvent(new EventArgsOfClientProgress( "file", methonInfo, arg1)); }; if (!string.IsNullOrEmpty(file.ContentType)) { content_file_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(file.ContentType); } content_.Add(content_file_, "file", file.FileName ?? "file"); } request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); var disposeResponse_ = true; try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) { headers_[item_.Key] = item_.Value; } } ProcessResponse(client_, response_); var status_ = (int)response_.StatusCode; if (status_ == 200) { var objectResponse_ = await ReadObjectResponseAsync <Tourism.STD.Models.InfoModel <NetCore.TempFileInfo> >(response_, headers_).ConfigureAwait(false); return(objectResponse_.Object); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally { if (disposeResponse_) { response_.Dispose(); } } } } finally { if (disposeClient_) { client_.Dispose(); } } }
public async Task <string> GetRecono([FromForm] string param, [FromForm] string paramImagen) { //this.infoPopup.ShowOnPageLoad = false; try { string paramImagen2 = JsonConvert.DeserializeObject <string>(paramImagen.ToString()); System.Net.HttpWebRequest request = null; System.Net.HttpWebResponse response = null; System.IO.Stream requestStream = null; byte[] bytes = null; string resultado = ""; byte[] data = System.Convert.FromBase64String(paramImagen2.ToString()); string url = "https://api.luxand.cloud/photo/search"; System.Net.ServicePointManager.SecurityProtocol = (System.Net.SecurityProtocolType) 3072; System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(); client.DefaultRequestHeaders.Add("token", "f579e24b9b094e4a9eaabf6c5477bd1a"); Stream fileStream = new MemoryStream(data); System.Net.Http.HttpContent fileStreamContent = new System.Net.Http.StreamContent(fileStream); using (var formData = new System.Net.Http.MultipartFormDataContent()) { formData.Add(fileStreamContent, "photo", "file1"); var response2 = await client.PostAsync(url, formData); if (!response2.IsSuccessStatusCode) { return(null); } return(await response2.Content.ReadAsStringAsync()); } //bytes = System.Text.Encoding.ASCII.GetBytes("photo=" + data); //request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); //request.Method = "POST"; //request.Headers.Add("token", "f579e24b9b094e4a9eaabf6c5477bd1a"); //request.ContentLength = bytes.Length; //request.ContentType = "multipart/form-data"; //requestStream = request.GetRequestStream(); //requestStream.Write(bytes, 0, bytes.Length); //requestStream.Close(); //request.Timeout = 15000; //response = (System.Net.HttpWebResponse)request.GetResponse(); //if (response.StatusCode == System.Net.HttpStatusCode.OK) //{ // System.IO.Stream responseStream = response.GetResponseStream(); // System.IO.StreamReader reader = new System.IO.StreamReader(responseStream); // resultado = reader.ReadToEnd(); // return resultado; //} } catch (Exception ex) { return("ERROR"); } return("ERROR"); }
/// <summary>uploads an image</summary> /// <param name="petId">ID of pet to update</param> /// <param name="additionalMetadata">Additional data to pass to server</param> /// <param name="file">file to upload</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>successful operation</returns> /// <exception cref="SwaggerException">A server side error occurred.</exception> public async System.Threading.Tasks.Task<ApiResponse> UploadFileAsync(int petId, string additionalMetadata, FileParameter file, System.Threading.CancellationToken cancellationToken) { var url_ = string.Format("{0}/{1}", BaseUrl, "pet/{petId}/uploadImage"); if (petId == null) throw new System.ArgumentNullException("petId"); url_ = url_.Replace("{petId}", System.Uri.EscapeDataString(petId.ToString())); using (var client_ = new System.Net.Http.HttpClient()) { var request_ = new System.Net.Http.HttpRequestMessage(); PrepareRequest(client_, ref url_); var content_ = new System.Net.Http.MultipartFormDataContent(); if (additionalMetadata != null) content_.Add(new System.Net.Http.StringContent(additionalMetadata.ToString()), "additionalMetadata"); if (file != null) content_.Add(new System.Net.Http.StreamContent(file.Data), "file", file.FileName ?? "file"); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseContentRead, cancellationToken).ConfigureAwait(false); ProcessResponse(client_, response_); var responseData_ = await response_.Content.ReadAsByteArrayAsync().ConfigureAwait(false); var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "200") { var result_ = default(ApiResponse); try { if (responseData_.Length > 0) result_ = Newtonsoft.Json.JsonConvert.DeserializeObject<ApiResponse>(System.Text.Encoding.UTF8.GetString(responseData_, 0, responseData_.Length)); return result_; } catch (System.Exception exception) { throw new SwaggerException("Could not deserialize the response body.", status_, responseData_, exception); } } else if (status_ != "200" && status_ != "204") throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", status_, responseData_, null); return default(ApiResponse); } }
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <summary>上传用户头像和名字</summary> /// <param name="name">用户名称</param> /// <param name="imgBase">头像base64</param> /// <exception cref="ApiException">A server side error occurred.</exception> public async System.Threading.Tasks.Task <Tourism.STD.Models.InfoModel <System.String> > UserImgAsync(string name, string imgBase, System.Threading.CancellationToken cancellationToken) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append("SmallAppApi/User/UserImg"); var client_ = _httpClient; var disposeClient_ = false; try { using (var request_ = await CreateHttpRequestMessageAsync(cancellationToken).ConfigureAwait(false)) { var boundary_ = System.Guid.NewGuid().ToString(); var content_ = new System.Net.Http.MultipartFormDataContent(boundary_); content_.Headers.Remove("Content-Type"); content_.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary_); if (name != null) { content_.Add(new System.Net.Http.StringContent(ConvertToString(name, System.Globalization.CultureInfo.InvariantCulture)), "Name"); } if (imgBase != null) { content_.Add(new System.Net.Http.StringContent(ConvertToString(imgBase, System.Globalization.CultureInfo.InvariantCulture)), "ImgBase"); } request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); var disposeResponse_ = true; try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) { headers_[item_.Key] = item_.Value; } } ProcessResponse(client_, response_); var status_ = (int)response_.StatusCode; if (status_ == 200) { var objectResponse_ = await ReadObjectResponseAsync <Tourism.STD.Models.InfoModel <System.String> >(response_, headers_).ConfigureAwait(false); return(objectResponse_.Object); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally { if (disposeResponse_) { response_.Dispose(); } } } } finally { if (disposeClient_) { client_.Dispose(); } } }
/// <summary>Submits a file for evaluation.</summary> /// <param name="file">the file to evaluate</param> /// <param name="correlationID">the correlation ID</param> /// <returns>the ID of the evaluation</returns> /// <exception cref="ApiClientException">A server side error occurred.</exception> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> public async System.Threading.Tasks.Task <string> SubmitAsync(FileParameter file, string correlationID = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/eval?"); if (correlationID != null) { urlBuilder_.Append("correlationID=").Append(System.Uri.EscapeDataString(ConvertToString(correlationID, System.Globalization.CultureInfo.InvariantCulture))).Append("&"); } urlBuilder_.Length--; var client_ = _httpClient; try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { var boundary_ = System.Guid.NewGuid().ToString(); var content_ = new System.Net.Http.MultipartFormDataContent(boundary_); content_.Headers.Remove("Content-Type"); content_.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary_); if (file != null) { content_.Add(new System.Net.Http.StreamContent(file.Data), "file", file.FileName ?? "file"); } request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); request_.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) { headers_[item_.Key] = item_.Value; } } ProcessResponse(client_, response_); var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "409") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new ApiClientException("An evaluation with a duplicate correlation ID has been submitted.", (int)response_.StatusCode, responseData_, headers_, null); } else if (status_ == "401") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new ApiClientException("Authentication is required and/or has failed.", (int)response_.StatusCode, responseData_, headers_, null); } else if (status_ == "403") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new ApiClientException("The user is not permitted to perform this operation.", (int)response_.StatusCode, responseData_, headers_, null); } else if (status_ == "500") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new ApiClientException("An internal error has occurred.", (int)response_.StatusCode, responseData_, headers_, null); } else if (status_ == "201") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); var result_ = default(string); try { result_ = Newtonsoft.Json.JsonConvert.DeserializeObject <string>(responseData_, _settings.Value); return(result_); } catch (System.Exception exception_) { throw new ApiClientException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_); } } else if (status_ != "200" && status_ != "204") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new ApiClientException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null); } return(default(string)); } finally { if (response_ != null) { response_.Dispose(); } } } } finally { } }
/// <summary> /// Adds the provided images to the current project iteration /// </summary> /// <param name='projectId'> /// The project id. /// </param> /// <param name='imageData'> /// </param> /// <param name='tagIds'> /// The tags ids to associate with the image batch. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <HttpOperationResponse <CreateImageSummaryModel> > CreateImagesFromDataWithHttpMessagesAsync(System.Guid projectId, IEnumerable <Stream> imageData, IList <Guid> tagIds = default(IList <Guid>), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (imageData == null) { throw new ValidationException(ValidationRules.CannotBeNull, "imageData"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("projectId", projectId); tracingParameters.Add("tagIds", tagIds); tracingParameters.Add("imageData", imageData); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PostImages", tracingParameters); } // Construct URL var _baseUrl = BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "projects/{projectId}/images/image").ToString(); _url = _url.Replace("{projectId}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(projectId, SerializationSettings).Trim('"'))); List <string> _queryParameters = new List <string>(); if (tagIds != null) { if (tagIds.Count == 0) { _queryParameters.Add(string.Format("tagIds={0}", System.Uri.EscapeDataString(string.Empty))); } else { foreach (var _item in tagIds) { _queryParameters.Add(string.Format("tagIds={0}", System.Uri.EscapeDataString(_item.ToString() ?? string.Empty))); } } } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; System.Net.Http.MultipartFormDataContent _multiPartContent = new System.Net.Http.MultipartFormDataContent(); if (imageData != null) { foreach (var image in imageData) { System.Net.Http.StreamContent _imageData = new System.Net.Http.StreamContent(image); _imageData.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream"); FileStream _imageDataAsFileStream = image as FileStream; if (_imageDataAsFileStream != null) { System.Net.Http.Headers.ContentDispositionHeaderValue _contentDispositionHeaderValue = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data"); _contentDispositionHeaderValue.Name = "imageData"; _contentDispositionHeaderValue.FileName = _imageDataAsFileStream.Name; _imageData.Headers.ContentDisposition = _contentDispositionHeaderValue; } _multiPartContent.Add(_imageData, "imageData"); } } _httpRequest.Content = _multiPartContent; // Set Credentials if (Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse <CreateImageSummaryModel>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject <CreateImageSummaryModel>(_responseContent, DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }