static async void upload_image(string path) { Console.WriteLine("Uploading {0}", path); try { using (var client = new HttpClient()) { using (var stream = File.OpenRead(path)) { var content = new MultipartFormDataContent(); var file_content = new ByteArrayContent(new StreamContent(stream).ReadAsByteArrayAsync().Result); file_content.Headers.ContentType = new MediaTypeHeaderValue("image/png"); file_content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "screenshot.png", Name = "foo", }; content.Add(file_content); client.BaseAddress = new Uri("https://pajlada.se/poe/imgup/"); var response = await client.PostAsync("upload.php", content); response.EnsureSuccessStatusCode(); Console.WriteLine("Done"); } } } catch (Exception) { Console.WriteLine("Something went wrong while uploading the image"); } }
public Stream Upload(string url, string filename, Stream fileStream) { HttpContent stringContent = new StringContent(filename); HttpContent fileStreamContent = new StreamContent(fileStream); using (var handler = new ProgressMessageHandler()) using (var client = HttpClientFactory.Create(handler)) using (var formData = new MultipartFormDataContent()) { client.Timeout = new TimeSpan(1, 0, 0); // 1 hour should be enough probably formData.Add(fileStreamContent, "file", filename); handler.HttpSendProgress += (s, e) => { float prog = (float)e.BytesTransferred / (float)fileStream.Length; prog = prog > 1 ? 1 : prog; if (FileProgress != null) FileProgress(filename, prog); }; var response_raw = client.PostAsync(url, formData); var response = response_raw.Result; if (!response.IsSuccessStatusCode) { return null; } return response.Content.ReadAsStreamAsync().Result; } }
public async Task<Models.Media> File(Stream fileStream, string name = "", string description = "", string projectId = null) { using (var formData = new MultipartFormDataContent()) { AddStringContent(formData, _client.Authentication.FieldName, _client.Authentication.Value); AddStringContent(formData, "project_id", projectId); AddStringContent(formData, "name", name); AddStringContent(formData, "description", description); // Add the file stream var fileContent = new StreamContent(fileStream); fileContent.Headers.Add("Content-Type", "application/octet-stream"); fileContent.Headers.Add("Content-Disposition", "form-data; name=\"file\"; filename=\"" + name + "\""); formData.Add(fileContent, "file", name); // HttpClient problem workaround var boundaryValue = formData.Headers.ContentType.Parameters.FirstOrDefault(p => p.Name == "boundary"); if (boundaryValue != null) { boundaryValue.Value = boundaryValue.Value.Replace("\"", string.Empty); } // Upload the file var response = await _client.Post(Client.UploadUrl, formData); return _client.Hydrate<Models.Media>(response); } }
//TODO(csMACnz): change from bool to Unit or a simplified Result<TError> as a thing? public Result<bool, string> Upload(string fileData) { using (HttpContent stringContent = new StringContent(fileData)) { using (var client = new HttpClient()) using (var formData = new MultipartFormDataContent()) { formData.Add(stringContent, "json_file", "coverage.json"); var response = client.PostAsync(RequestUri, formData).Result; if (!response.IsSuccessStatusCode) { var content = response.Content.ReadAsStringAsync().Result; var message = TryGetJsonMessageFromResponse(content).ValueOr(content); if (message.Length > 200) { message = message.Substring(0, 200); } return string.Format("{0} - {1}", response.StatusCode, message); } return true; } } }
/// <summary> /// Assincronouslly send the fields in the list to webServer in url parameter /// NextStep: add a percentage of uploaded data! /// </summary> /// <param name="fields"></param> /// <param name="url"></param> /// <returns></returns> internal static async Task<string> send(List<field> fields, string url) { HttpClient httpClient = new HttpClient(); MultipartFormDataContent form = new MultipartFormDataContent(); foreach(field f in fields) { if(f.kind == fieldKind.text) { form.Add(new StringContent(f.content), f.name); } else if (f.kind == fieldKind.file) { HttpContent content = new ByteArrayContent(f.bytes); content.Headers.Add("Content-Type", f.contentType); form.Add(content, f.name, f.fileName); } } HttpResponseMessage response = await httpClient.PostAsync(url, form); response.EnsureSuccessStatusCode(); httpClient.Dispose(); return response.Content.ReadAsStringAsync().Result; }
public CommentResult Create(string projectId, string taskId, string text, string filePath) { var message = new HttpRequestMessage(); var content = new MultipartFormDataContent(); content.Add(new StringContent(text ?? string.Empty), "Text"); if (!string.IsNullOrEmpty(filePath)) { var filestream = new FileStream(filePath, FileMode.Open); var fileName = System.IO.Path.GetFileName(filePath); content.Add(new StreamContent(filestream), "file", fileName); content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = fileName }; } message.Method = HttpMethod.Post; message.Content = content; message.RequestUri = new Uri(GetUrl(CommentActionUrls.New, projectId, taskId)); using (var client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization-Token", token); var result = client.SendAsync(message).Result; ValidationCheck(result); return result.Content.ReadAsAsync<CommentResult>().Result; } }
private static void SendImageSet(ImageSet imageSet) { var multipartContent = new MultipartFormDataContent(); var imageSetJson = JsonConvert.SerializeObject(imageSet, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }); multipartContent.Add(new StringContent(imageSetJson, Encoding.UTF8, "application/json"), "imageset"); int counter = 0; foreach (var image in imageSet.Images) { var imageContent = new ByteArrayContent(image.ImageData); imageContent.Headers.ContentType = new MediaTypeHeaderValue(image.MimeType); multipartContent.Add(imageContent, "image" + counter++, image.FileName); } var response = new HttpClient() .PostAsync("http://localhost:53908/api/send", multipartContent) .Result; var responseContent = response.Content.ReadAsStringAsync().Result; Trace.Write(responseContent); }
public void GetStreamValidation() { Stream stream0 = null; Stream stream1 = null; try { MultipartFormDataContent content = new MultipartFormDataContent(); content.Add(new StringContent("Not a file"), "notafile"); content.Add(new StringContent("This is a file"), "file", "filename"); MultipartFileStreamProvider instance = new MultipartFileStreamProvider(Path.GetTempPath()); stream0 = instance.GetStream(content.ElementAt(0).Headers); Assert.IsType<FileStream>(stream0); stream1 = instance.GetStream(content.ElementAt(1).Headers); Assert.IsType<FileStream>(stream1); Assert.Equal(2, instance.BodyPartFileNames.Count); Assert.Contains("BodyPart", instance.BodyPartFileNames[0]); Assert.Contains("BodyPart", instance.BodyPartFileNames[1]); } finally { if (stream0 != null) { stream0.Close(); } if (stream1 != null) { stream1.Close(); } } }
public async Task <string> UploadFirmware(string fileName, Stream binFile) { CameraInfo.UpdatingFirmware = true; try { string requestStr = String.Format("http://{0}/upgrade_firmware.cgi", CameraInfo.IpAddress); var fileContents = new System.Net.Http.StreamContent(binFile); fileContents.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream"); var content = new System.Net.Http.MultipartFormDataContent("---------------------------7deef381d07b6"); content.Add(fileContents, "file", fileName); // override the content disposition var contentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data"); contentDisposition.Name = "file"; contentDisposition.FileName = fileName; fileContents.Headers.ContentDisposition = contentDisposition; return(await PostFormRequest(requestStr, content)); } finally { // actually, let's wait for next ping to succeed which means the reboot is finished. // CameraInfo.UpdatingFirmware = false; } }
//Sends the request with all the headers and content public async Task send(){ HttpClientHandler handler = new HttpClientHandler {UseCookies = false}; //Needed to set cookies in bulk without them being ignored HttpClient client = new HttpClient(handler); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url); MultipartFormDataContent content = new MultipartFormDataContent(boundary); //Add the HTTP headers foreach (KeyValuePair<string, string> header in extraHeaders) { request.Headers.Add(header.Key, header.Value); } //Add the multipart content to an object foreach (RequestPart part in parts){ content.Add(createFileContent(new MemoryStream(part.data), part)); } request.Content = content; //Add the multipart data object to the HttpClient //Get and handle the response HttpResponseMessage httpResponse = await client.SendAsync(request); reasonPhrase = httpResponse.ReasonPhrase; statusCode = (int)httpResponse.StatusCode; if (httpResponse.Content.Headers.ContentEncoding.ToString() == "gzip"){ Stream responseStream = await httpResponse.Content.ReadAsStreamAsync(); response = new StreamReader(new GZipStream(responseStream, CompressionMode.Decompress), Encoding.UTF8).ReadToEnd(); //Decompress and translate the response to a string } else{ response = await httpResponse.Content.ReadAsStringAsync(); } }
static async void RunClient() { HttpClient client = new HttpClient(); // Issue MIME multipart POST request with a MIME multipart message containing a single // body part with StringContent. StringContent content = new StringContent("Hello World", Encoding.UTF8, "text/plain"); MultipartFormDataContent formData = new MultipartFormDataContent(); formData.Add(content, "file", "HelloWorld.txt"); Console.WriteLine("Uploading data to store..."); HttpResponseMessage postResponse = await client.PostAsync(_addres, formData); postResponse.EnsureSuccessStatusCode(); JArray postResult = await postResponse.Content.ReadAsAsync<JArray>(); string location = postResult[0].Value<string>("Location"); // Issue GET request to get the content back from the store Console.WriteLine("Retrieving data from store: {0}", location); HttpResponseMessage getResponse = await client.GetAsync(location); getResponse.EnsureSuccessStatusCode(); string result = await getResponse.Content.ReadAsStringAsync(); Console.WriteLine("Received response: {0}", result); }
public static RequestResponse Sign(byte[] document, string phone, string code) { using (var client = new HttpClient()) { using (var content = new MultipartFormDataContent("Upload----" + DateTime.Now)) { content.Add(new StringContent("pdf"), "type"); content.Add(new StringContent(phone), "phone"); content.Add(new StringContent(code), "code"); content.Add(new StringContent("true"), "timestamp"); content.Add(new StringContent("Vardas Pavardenis"), "pdf[contact]"); content.Add(new StringContent("Test"), "pdf[reason]"); content.Add(new StringContent("Vilnius"), "pdf[location]"); content.Add(new StringContent("test.pdf"), "pdf[files][0][name]"); content.Add(new StringContent(Convert.ToBase64String(document)), "pdf[files][0][content]"); content.Add( new StringContent( BitConverter.ToString(SHA1.Create().ComputeHash(document)).Replace("-", "").ToLower()), "pdf[files][0][digest]"); using ( var message = client.PostAsync("https://developers.isign.io/mobile/sign.json?access_token=" + Api.accessToken, content)) { var input = message.Result; var serializator = new DataContractJsonSerializer(typeof(RequestResponse)); return (RequestResponse)serializator.ReadObject(input.Content.ReadAsStreamAsync().Result); } } } }
static void Main(string[] args) { var message = new HttpRequestMessage(); var content = new MultipartFormDataContent(); var files = new List<string> {"WebApiDoc01.png", "WebApiDoc02.png"}; foreach (var file in files) { var filestream = new FileStream(file, FileMode.Open); var fileName = System.IO.Path.GetFileName(file); content.Add(new StreamContent(filestream), "file", fileName); } message.Method = HttpMethod.Post; message.Content = content; message.RequestUri = new Uri("http://localhost:8081/api/test/filesNoContentType"); var client = new HttpClient(); client.SendAsync(message).ContinueWith(task => { if (task.Result.IsSuccessStatusCode) { var result = task.Result; Console.WriteLine(result); } }); Console.ReadLine(); }
public void Should_Accept_Only_Text_Content() { // Arrange Mock<IStorageRepository> storageRepositoryMock; Mock<IFileProcessor> fileProcessorMock; Mock<IChecksumCalculator> checksumCalculatorMock; Mock<IMetadataRepository> metadataRepositoryMock; var controller = this.ConfigureController(out storageRepositoryMock, out fileProcessorMock, out checksumCalculatorMock, out metadataRepositoryMock); var multipartContent = new MultipartFormDataContent(); var binaryContent = Enumerable.Repeat(Enumerable.Range(14, 255).ToArray(), 20).SelectMany(x => x.Select(y => y)).Select(x=>(byte)x).ToArray(); var fileContent = new ByteArrayContent(binaryContent); fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = "Test.txt" }; fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("something/that_we_dont_expect"); multipartContent.Add(fileContent); controller.Request.Content = multipartContent; // Act Task<IHttpActionResult> task = controller.Post(); task.Wait(); // Assert GenericValueResult<List<MetadataInfo>> result = task.Result as GenericValueResult<List<MetadataInfo>>; result.Should().NotBeNull("Wrong data type was returned from the controller"); var t = result.Value as IEnumerable<Models.MetadataInfo>; t.Should().NotBeNull("Wrong data type was returned as a result of controller's work"); var informationFromService = t.First(); informationFromService.Id.Should().NotHaveValue(); informationFromService.ProcessingResult.Should().Be(UploadController.ContentTypeCannotBeAcceptedMessage); }
//TODO: Update response object public static async Task<Upload> media_upload(this Api api, Command command, long total_bytes, string media_data = "", byte[] media = null, string media_type = "", long media_id = -1, int segment_index = 0, IEnumerable<string> additional_owners = null) { var uri = "https://upload.twitter.com/1.1/media/upload.json"; var client = new HttpClient(new MessageHandler(api.Token)); var request = new HttpRequestMessage(HttpMethod.Post, uri); var content = new MultipartFormDataContent(); content.Add(new StringContent(command.ToString()), "command"); if (media_id != -1) content.Add(new StringContent(media_id.ToString()), "media_id"); if (segment_index != 0) content.Add(new StringContent(segment_index.ToString()), "segment_index"); if (!string.IsNullOrEmpty(media_type)) content.Add(new StringContent(media_type), "media_type"); if (total_bytes != -1) content.Add(new StringContent(total_bytes.ToString()), "total_bytes"); if (!string.IsNullOrEmpty(media_data)) content.Add(new StringContent(media_data), "media_data"); if (media != null) content.Add(new ByteArrayContent(media), "media"); if (additional_owners != null && additional_owners.Any()) { content.Add(new StringContent(string.Join(",", additional_owners)), "additional_owners"); } request.Content = content; var response = await client.SendAsync(request); var json = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject<Upload>(json); return result; }
private void AttachFiles(IMail message, MultipartFormDataContent content) { var files = FetchFileBodies(message); foreach (var file in files) { var ifile = file.Value; var fileContent = new StreamContent(ifile.OpenAsync(FileAccess.Read).Result); fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "files[" + ifile.Name + "]", FileName = ifile.Name }; fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream"); content.Add(fileContent); } var streamingFiles = FetchStreamingFileBodies(message); foreach (KeyValuePair<string, MemoryStream> file in streamingFiles) { var name = file.Key; var stream = file.Value; var fileContent = new StreamContent(stream); fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "files[" + name + "]", FileName = name }; fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream"); content.Add(fileContent); } }
/// <summary> /// Uploads a file to the specified endpoint /// </summary> /// <param name="token">The authentication token</param> /// <param name="path">The endpoint to invoke</param> /// <param name="filename">The local file system path to the file</param> /// <param name="contentType">The mime-type</param> /// <returns>The result of the operation</returns> internal async Task<string> UploadFile(AuthToken token, string path, string filename, string contentType) { using (HttpClient client = new HttpClient()) { HttpRequestMessage message = new HttpRequestMessage(); message.Method = HttpMethod.Post; message.RequestUri = new Uri($"{_baseAddress}/{path}"); message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token.Token); var content = new MultipartFormDataContent("Upload----" + DateTime.Now.ToString(CultureInfo.InvariantCulture)); var streamContent = new StreamContent(File.OpenRead(filename)); streamContent.Headers.ContentType = new MediaTypeHeaderValue(contentType); content.Add(streamContent, Path.GetFileName(filename), Path.GetFileName(filename)); message.Content = content; var response = await client.SendAsync(message); if (response.IsSuccessStatusCode) { return await response.Content.ReadAsStringAsync(); } else { throw new ApplicationException($"{response.StatusCode} {response.ReasonPhrase}"); } } }
public async Task<string> SendPostFileRequest(string url, NameValueCollection formData, IEnumerable<KeyValuePair<string, byte[]>> fileData) { // this.txtResponse.Text = string.Empty; using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));//设定要响应的数据格式 using (var content = new MultipartFormDataContent())//表明是通过multipart/form-data的方式上传数据 { var formDatas = this.GetFormDataByteArrayContent(formData);//获取键值集合对应的ByteArrayContent集合 var files = this.GetFileByteArrayContent(fileData);//获取文件集合对应的ByteArrayContent集合 Action<List<ByteArrayContent>> act = (dataContents) => {//声明一个委托,该委托的作用就是将ByteArrayContent集合加入到MultipartFormDataContent中 foreach (var byteArrayContent in dataContents) { content.Add(byteArrayContent); } }; act(formDatas);//执行act act(files);//执行act try { var response = await client.PostAsync(url, content);//post请求 response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync(); } catch (Exception ex) { return null; } } } }
private async static Task<bool> SendMessageWithImageAsync(string message, string chatId, string messageId, Stream imageStream) { var tghttpClient = new HttpClient(); imageStream.Seek(0, SeekOrigin.Begin); var buf = ReadFully(imageStream); var imageContent = new ByteArrayContent(buf); imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/png"); // Send Message, as well as image var endpointUrl = new Uri(string.Format(RequestTemplate.RpcOpUrl, RequestTemplate.AppId, "sendPhoto")); var content = new MultipartFormDataContent(); /*content.Add(new FormUrlEncodedContent(new List<KeyValuePair<string,string>> { new KeyValuePair<string, string>("chat_id", chatId), new KeyValuePair<string, string>("reply_to_message_id", messageId), new KeyValuePair<string, string>("caption", message) }));*/ content.Add(imageContent, "photo", string.Format("{0}.png", Guid.NewGuid())); content.Add(new ByteArrayContent(Encoding.UTF8.GetBytes(chatId)),"chat_id"); content.Add(new ByteArrayContent(Encoding.UTF8.GetBytes(messageId)), "reply_to_message_id"); content.Add(new ByteArrayContent(Encoding.UTF8.GetBytes(message)), "aptiond"); var result = await tghttpClient.PostAsync(endpointUrl, content); var content2 = await result.Content.ReadAsStringAsync(); return result.IsSuccessStatusCode; }
public static async Task<ImgurEntity> UploadImgur(IRandomAccessStream fileStream) { try { var imageData = new byte[fileStream.Size]; for (int i = 0; i < imageData.Length; i++) { imageData[i] = (byte)fileStream.AsStreamForRead().ReadByte(); } var theAuthClient = new HttpClient(); var request = new HttpRequestMessage(HttpMethod.Post, "https://api.imgur.com/3/image"); request.Headers.Authorization = new AuthenticationHeaderValue("Client-ID", "e5c018ac1f4c157"); var form = new MultipartFormDataContent(); var t = new StreamContent(fileStream.AsStream()); // TODO: See if this is the correct way to use imgur's v3 api. I can't see why we would still need to convert images to base64. string base64Img = Convert.ToBase64String(imageData); t.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg"); form.Add(new StringContent(base64Img), @"image"); form.Add(new StringContent("file"), "type"); request.Content = form; HttpResponseMessage response = await theAuthClient.SendAsync(request); string responseString = await response.Content.ReadAsStringAsync(); if (responseString == null) return null; var imgurEntity = JsonConvert.DeserializeObject<ImgurEntity>(responseString); return imgurEntity; } catch (WebException) { } catch (IOException) { return null; } return null; }
public static void PostCreatedFiles(ConcurrentDictionary<string, LocalFile> files, string uploadUrl) { var localFiles = files.ToList(); // Create post content var content = new MultipartFormDataContent(); // Check we have content to send if (!LoadFileToDataContent(content, files.Select(x => x.Value).ToList())) { Console.WriteLine("Failed to load file or no content as loaded. Cancel upload"); return; } SendPostData(content, uploadUrl); if (BaseConfig.Synchronize) { localFiles.ForEach(x => x.Value.Synchronized = true); } else { // Remove files from queue foreach (var file in localFiles) { LocalFile deleted; if (!files.TryRemove(file.Key, out deleted)) { Console.WriteLine("Failed to remove"); } } } }
private void AttachFiles(ISendGrid message, MultipartFormDataContent content) { var files = FetchFileBodies(message); foreach (var file in files) { var fs = new FileStream(file.Key, FileMode.Open, FileAccess.Read); var fileContent = new StreamContent(fs); fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "files[" + Path.GetFileName(file.Key) + "]", FileName = Path.GetFileName(file.Key) }; fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream"); content.Add(fileContent); } var streamingFiles = FetchStreamingFileBodies(message); foreach (var file in streamingFiles) { var stream = file.Value; var fileContent = new StreamContent(stream); fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "files[" + Path.GetFileName(file.Key) + "]", FileName = Path.GetFileName(file.Key) }; fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream"); content.Add(fileContent); } }
public string GetBalance() { try { MultipartFormDataContent content = new MultipartFormDataContent(); var values = new[] { new KeyValuePair<string, string>("function", "balance"), new KeyValuePair<string, string>("username", username), new KeyValuePair<string, string>("password", password), new KeyValuePair<string, string>("submit", "Send"), }; foreach (var keyValuePair in values) { content.Add(new StringContent(keyValuePair.Value), String.Format("\"{0}\"", keyValuePair.Key)); } var result = httpClient.PostAsync("http://poster.de-captcher.com/", content).Result; return result.Content.ReadAsStringAsync().Result; } catch { return ""; } }
public async Task<string> CreatePageForIncidentAsync(string siteRootDirectory, string sectionId, Incident incident, IEnumerable<FileContent> inspectionPhotos, IEnumerable<Video> incidentVideos) { var templateFile = Path.Combine(siteRootDirectory, @"Templates\IncidentOneNotePage.cshtml"); var template = System.IO.File.ReadAllText(templateFile); var viewBag = new RazorEngine.Templating.DynamicViewBag(); viewBag.AddValue("InspectionPhotos", inspectionPhotos); viewBag.AddValue("IncidentVideos", incidentVideos); var html = RazorEngine.Engine.Razor.RunCompile(template, "IncidentOneNotePage", typeof(Incident), incident, viewBag); var content = new MultipartFormDataContent(); content.Add(new StringContent(html, Encoding.UTF8, "text/html"), "Presentation"); foreach (var image in inspectionPhotos) { var itemContent = new ByteArrayContent(image.Bytes); var contentType = MimeMapping.GetMimeMapping(image.Name); itemContent.Headers.ContentType = new MediaTypeHeaderValue(contentType); content.Add(itemContent, image.Id); } this.pageEndPoint = string.Format("{0}/sections/{1}/pages", serviceBaseUrl, sectionId); var requestMessage = new HttpRequestMessage(HttpMethod.Post, pageEndPoint); requestMessage.Content = content; var responseMessage = await HttpSendAsync(requestMessage, accessToken); if (responseMessage.StatusCode != System.Net.HttpStatusCode.Created) throw new HttpResponseException(responseMessage.StatusCode); var reponseObject = await GetReponseObjectAsync(responseMessage); return (string)reponseObject.links.oneNoteWebUrl.href; }
public string GetCaptchaStr(byte[] imagefile) { try { //var result = httpClient.GetAsync("http://poster.de-captcher.com/").Result; //result.Dispose(); MultipartFormDataContent content = new MultipartFormDataContent(); var values = new[] { new KeyValuePair<string, string>("function", "picture2"), new KeyValuePair<string, string>("username", username), new KeyValuePair<string, string>("password", password), new KeyValuePair<string, string>("pict_type", "0"), new KeyValuePair<string, string>("submit", "Send"), }; foreach (var keyValuePair in values) { content.Add(new StringContent(keyValuePair.Value), String.Format("\"{0}\"", keyValuePair.Key)); } content.Add(new StreamContent(new MemoryStream(imagefile)), "pict"); var result = httpClient.PostAsync("http://poster.de-captcher.com/", content).Result; string strContent = result.Content.ReadAsStringAsync().Result; major = strContent.Split('|')[1]; min = strContent.Split('|')[2]; return strContent.Split('|')[5]; } catch { return ""; } }
/// <summary> /// メディア付きのツイートを投稿します。 /// </summary> public static async Task<Status> UpdateStatus( this TwitterToken token, string status, string[] mediaPaths, StatusId? inReplyToStatusId = null) { // media が空だったら通常の投稿に切り替える if (!mediaPaths.HasValue()) return await token.UpdateStatus(status, inReplyToStatusId); var endpoint = token.Endpoints["statuses/update_with_media"]; using (var client = token.GetClient()) using (var content = new MultipartFormDataContent { { new StringContent(status), "\"status\"" } }) { if (inReplyToStatusId.HasValue) { content.Add(new StringContent(inReplyToStatusId.ToString()), "\"in_reply_to_status_id\""); } foreach (var path in mediaPaths) { var media = File.ReadAllBytes(path); var filename = Path.GetFileName(path); content.Add(new ByteArrayContent(media), "media[]", "\"" + filename + "\""); } return await client.PostAsyncEx( endpoint.Definition.Url, content, res => endpoint.RateLimit.Set(res.Headers), json => Status.Parse(json, StatusSource.Update), () => token.FallbackToken.UpdateStatus(status, mediaPaths, inReplyToStatusId)); } }
public static void GetPackagesStatus() { var client = new HttpClient(); List<Package> _packages = Databases.serverModel.PackageSet.Where(x => x.Labeled == true && x.Package_id == null).ToList(); foreach (Package p in _packages) { MediaLogBarcodePackage package = new MediaLogBarcodePackage(); package.user = "******"; package.package = new MediaLogBarcodePack { package_id = p.Temporary_package_id }; string json = JsonConvert.SerializeObject(package); MultipartFormDataContent form = new MultipartFormDataContent(); StringContent cont = new StringContent(json); form.Add(new StringContent(json), "pack"); HttpResponseMessage response = client.PostAsync("http://csomagteszt.media-log.hu/packages/get_status", form).Result; response.EnsureSuccessStatusCode(); string sd = response.Content.ReadAsStringAsync().Result;//164058, 000000000009 if (sd.StartsWith("OK")) { p.Status = sd.Remove(0, 4); Databases.serverModel.SaveChanges(); } else { //gáz van } } }
private static async Task<HttpStatusCode> Upload() { var files = new List<string>(); files.Add(@"c:\temp\midi.xml"); files.Add(@"c:\temp\maxi.xml"); files.Add(@"c:\temp\efti.xml"); var apiUri = string.Format("https://api-dev.qbranch.se/api/customers/{0}/tickets/{1}/attachments", customerId, ticketId); var message = new HttpRequestMessage(); message.RequestUri = new Uri(apiUri); message.Headers.Add("qnet-api-key", apiKey); message.Method = HttpMethod.Post; var content = new MultipartFormDataContent(); foreach (var file in files) { var filestream = new FileStream(file, FileMode.Open); var fileName = Path.GetFileName(file); content.Add(new StreamContent(filestream), "file", fileName); } message.Content = content; using (var client = new HttpClient()) { var response = await client.SendAsync(message); return response.StatusCode; } }
private static async Task UploadFileToJira(string file) { var url = IssueUrl(file); var response = await client.GetStringAsync(url); dynamic issue = JObject.Parse(response); var info = GetIssueInfo(file); foreach (var attachment in issue.fields.attachment) { if (attachment.filename != info.OriginalFilename) continue; if (!options.Overwrite) { Console.WriteLine($"{issue.key} already contains '{info.OriginalFilename}' skipping..."); return; } Console.WriteLine($"{issue.key} Replacing existing attachment '{info.OriginalFilename}'"); await client.DeleteAsync(attachment.self.ToString()); } Console.WriteLine($"{issue.key} uploading '{info.OriginalFilename}'"); var form = new MultipartFormDataContent { { new StreamContent(File.OpenRead(file)), "\"file\"", info.OriginalFilename } }; await client.PostAsync(IssueUrl(file) + "/attachments", form); }
public static byte[] PostMultipartFormDataBodyReturnBytes(string url, IDictionary <string, object> values, IList <string> fileNames, Encoding encoding = null, IDictionary <string, string> headers = null, string referrer = null, string accept = null) { var content = new System.Net.Http.MultipartFormDataContent(); if (encoding == null) { encoding = Encoding.UTF8; } int i = 0; foreach (var item in values) { if (item.Value == null) { content.Add(new System.Net.Http.StringContent(""), item.Key); } else if (item.Value.GetType() == typeof(byte[])) { var cc = new System.Net.Http.StreamContent(new MemoryStream((byte[])item.Value)); cc.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpeg"); content.Add(cc, item.Key, fileNames[i]); i++; } else if (item.Value.GetType() == typeof(DateTime)) { content.Add(new System.Net.Http.StringContent(((DateTime)item.Value).ToString("yyyy-MM-dd HH:mm:ss")), item.Key); } else if (item.Value is Enum) { content.Add(new System.Net.Http.StringContent(((int)item.Value).ToString()), item.Key); } else if (item.Value is double) { content.Add(new System.Net.Http.StringContent(((double)item.Value).ToString("F2")), item.Key); } else if (item.Value is float) { content.Add(new System.Net.Http.StringContent(((float)item.Value).ToString("F2")), item.Key); } else { content.Add(new System.Net.Http.StringContent(item.Value.ToString()), item.Key); } } var client = SetupClient(headers, referrer, accept); var ret = client.PostAsync(url, content).Result; if (ret.IsSuccessStatusCode == false) { throw new Exception("HTTP请求错误:" + ret.StatusCode); } var data = ret.Content.ReadAsByteArrayAsync().Result; return(data); }
public Result UploadFile(string pathFile, Stream stream) { var result = new Result(); var content = new System.Net.Http.MultipartFormDataContent(); content.Add(new System.Net.Http.StreamContent(stream)); var msg = hc.PostAsync(pathFile, content).Result.Content.ReadAsStringAsync().Result; if (!msg.Contains("error")) { result.Status = true; } return(result); }
public static byte[] PostMultipartFormDataBodyReturnBytes(string url, IDictionary <string, object> values, Encoding encoding = null, IDictionary <string, string> headers = null, string referrer = null, string accept = null) { var content = new System.Net.Http.MultipartFormDataContent(); encoding = encoding ?? Encoding.UTF8; foreach (var item in values) { if (item.Value == null) { throw new Exception("参数的值为NULL"); } else if (item.Value is byte) { var cc = new System.Net.Http.StreamContent(new MemoryStream((byte[])item.Value)); cc.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpeg"); content.Add(cc, item.Key, item.Key); } else if (item.Value is string) { content.Add(new System.Net.Http.StringContent(item.Value as string, encoding ?? Encoding.UTF8, "application/x-www-form-urlencoded"), item.Key); } else { throw new Exception("不支持的类型:" + item.Value.GetType().FullName); } } var client = SetupClient(headers, referrer, accept); HttpResponseMessage ret = null; try { ret = client.PostAsync(url, content).Result; } catch (Exception ex) { throw GetOrignalException(ex); } if (ret.IsSuccessStatusCode == false) { throw new Exception("HTTP请求错误:" + ret.StatusCode); } var data = ret.Content.ReadAsByteArrayAsync().Result; return(data); }
internal override void WriteContent(HttpRequestMessage request) { var content = new System.Net.Http.MultipartFormDataContent(); foreach (var item in _contents) { if (item.Value is string s) { content.Add(new System.Net.Http.StringContent(s, Encoding.UTF8), item.Key); } else if (item.Value is FileContent file) { content.Add(new StreamContent(file.Steam), item.Key, file.FileName ?? item.Key); } } request.Content = content; }
public async Task <UploadPhotoResult> UploadPhoto(string url, string folderPhotoPath, byte[] photo) { HttpClient client = new HttpClient(); MultipartContent content = new System.Net.Http.MultipartFormDataContent(); var photoFile = new ByteArrayContent(photo); photoFile.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "photo", FileName = folderPhotoPath + "result.jpg", }; content.Add(photoFile); HttpResponseMessage response = await client.PostAsync(url, content); response.EnsureSuccessStatusCode(); var responseBody = await response.Content.ReadAsStringAsync(); return(JsonConvert.DeserializeObject <UploadPhotoResult>(responseBody)); }
public static async Task findPerson() {/* * var url = $"http://192.168.15.27:8090/person/find"; * HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); * request.Method = "POST"; * request.Credentials = CredentialCache.DefaultCredentials; * request.ContentType = "application/form-data"; * request.Accept = "application/json"; */ try { string baseUrl = "/person/find"; var parameters = new Dictionary <string, string>(); parameters.Add("pass", "87654321"); parameters.Add("id", "3"); System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(); client.BaseAddress = new Uri("http://192.168.15.27:8090" + baseUrl); System.Net.Http.MultipartFormDataContent form = new System.Net.Http.MultipartFormDataContent(); HttpContent DictionaryItems = new FormUrlEncodedContent((IEnumerable <KeyValuePair <string, string> >)parameters); form.Add(DictionaryItems, "personFind"); var response = await client.PostAsync("/person/find", form); var k = await response.Content.ReadAsStringAsync(); Console.WriteLine(response); Console.ReadKey(); } catch (Exception e) { } }
public void sendRequest( string method, Uri url, int requestId, string[][] headers, JObject data, string responseType, bool useIncrementalUpdates, int timeout) { if (method == null) { throw new ArgumentNullException(nameof(method)); } if (url == null) { throw new ArgumentNullException(nameof(url)); } if (responseType == null) { throw new ArgumentNullException(nameof(responseType)); } if (responseType != "text" && responseType != "base64") { throw new ArgumentOutOfRangeException(nameof(responseType)); } var request = new HttpRequestMessage(new HttpMethod(method), url); var headerData = default(HttpContentHeaderData); if (headers != null) { headerData = HttpContentHelpers.ExtractHeaders(headers); ApplyHeaders(request, headers); } if (data != null) { var body = data.Value <string>("string"); var uri = default(string); var formData = default(JArray); if (body != null) { if (headerData.ContentType == null) { OnRequestError(requestId, "Payload is set but no 'content-type' header specified.", false); return; } request.Content = HttpContentHelpers.CreateFromBody(headerData, body); } else if ((uri = data.Value <string>("uri")) != null) { if (headerData.ContentType == null) { OnRequestError(requestId, "Payload is set but no 'content-type' header specified.", false); return; } _tasks.AddAndInvokeAsync(requestId, token => ProcessRequestFromUriAsync( requestId, new Uri(uri), useIncrementalUpdates, timeout, request, responseType, token)); return; } else if ((formData = (JArray)data.GetValue("formData", StringComparison.Ordinal)) != null) { if (headerData.ContentType == null) { headerData.ContentType = "multipart/form-data"; } var formDataContent = new HttpMultipartFormDataContent(); foreach (var content in formData) { var fieldName = content.Value <string>("fieldName"); var stringContent = content.Value <string>("string"); if (stringContent != null) { formDataContent.Add(new HttpStringContent(stringContent), fieldName); } } request.Content = formDataContent; } } _tasks.AddAndInvokeAsync(requestId, async token => { using (request) { try { await ProcessRequestAsync( requestId, useIncrementalUpdates, timeout, request, responseType, token); } finally { var content = request.Content; if (content != null) { content.Dispose(); } } } }); }
public MediaPage() { InitializeComponent(); takePhoto.Clicked += async(sender, args) => { if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported) { DisplayAlert("No Camera", ":( No camera available.", "OK"); return; } var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions { Directory = "Test", SaveToAlbum = true, CompressionQuality = 75, CustomPhotoSize = 50, PhotoSize = PhotoSize.MaxWidthHeight, MaxWidthHeight = 2000, DefaultCamera = CameraDevice.Front }); if (file == null) { return; } DisplayAlert("File Location", file.Path, "OK"); image.Source = ImageSource.FromStream(() => { stream = file.GetStream(); file.Dispose(); return(stream); }); }; pickPhoto.Clicked += async(sender, args) => { if (!CrossMedia.Current.IsPickPhotoSupported) { DisplayAlert("Photos Not Supported", ":( Permission not granted to photos.", "OK"); return; } var file = await Plugin.Media.CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions { PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium, }); if (file == null) { return; } image.Source = ImageSource.FromStream(() => { stream = file.GetStream(); file.Dispose(); return(stream); }); }; takeVideo.Clicked += async(sender, args) => { if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakeVideoSupported) { DisplayAlert("No Camera", ":( No camera avaialble.", "OK"); return; } var file = await CrossMedia.Current.TakeVideoAsync(new Plugin.Media.Abstractions.StoreVideoOptions { Name = "video.mp4", Directory = "DefaultVideos", }); if (file == null) { return; } DisplayAlert("Video Recorded", "Location: " + file.Path, "OK"); file.Dispose(); }; pickVideo.Clicked += async(sender, args) => { if (!CrossMedia.Current.IsPickVideoSupported) { DisplayAlert("Videos Not Supported", ":( Permission not granted to videos.", "OK"); return; } var file = await CrossMedia.Current.PickVideoAsync(); if (file == null) { return; } DisplayAlert("Video Selected", "Location: " + file.Path, "OK"); file.Dispose(); }; sendfile.Clicked += async(sender, args) => { //todo put other your IIS s try { if (stream == null) { return; // user canceled file picking } using (HttpClient _httpClient = new HttpClient()) { var url = "https://localhost:44360/api/FileApi/save"; 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); content.Add(new System.Net.Http.StreamContent(stream)); await _httpClient.PostAsync(url, content); } } catch (Exception ex) { var exception = ex; DisplayAlert("Video Selected", "Location: " + ex.Message, "OK"); } }; }
public async void PostProcessing_ProcessesFormData_WithCustomMultipartFormDataStreamProvider() { // Arrange string tempPath = Path.GetTempPath(); int maxContents = 16; string contentFormat = "Content {0}"; string formNameFormat = "FormName_{0}"; string fileNameFormat = "FileName_{0}"; MultipartFormDataContent multipartContent = new MultipartFormDataContent(); // Create half contents for form data and the other half for file data. for (int index = 0; index < maxContents; index++) { string content = String.Format(contentFormat, index); string formName = String.Format(formNameFormat, index); if (index < maxContents / 2) { multipartContent.Add(new StringContent(content), formName); } else { string fileName = String.Format(fileNameFormat, index); multipartContent.Add(new StringContent(content), formName, fileName); } } CustomMultipartFormDataStreamProvider provider = new CustomMultipartFormDataStreamProvider(tempPath); foreach (HttpContent content in multipartContent) { provider.Contents.Add(content); using (provider.GetStream(multipartContent, content.Headers)) { } } // Act Task processingTask = provider.ExecutePostProcessingAsync(); await processingTask; // Assert Assert.Equal(TaskStatus.RanToCompletion, processingTask.Status); Assert.Equal(maxContents / 2, provider.FormData.Count); // half contents for form data for (int index = 0; index < maxContents / 2; index++) { string content = String.Format(contentFormat, index); string formName = String.Format(formNameFormat, index); Assert.Equal(content, provider.FormData[formName]); } // the other half for file data HttpContent[] contents = multipartContent.ToArray(); for (int index = maxContents / 2; index < maxContents; index++) { int fileDataIndex = index - (maxContents / 2); string fileName = String.Format(fileNameFormat, index); Assert.Equal(fileName, provider.FileData[fileDataIndex].LocalFileName); Assert.Same(contents[index].Headers, provider.FileData[fileDataIndex].Headers); } }
/// <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="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <HttpOperationResponse <Stream> > UploadFileWithHttpMessagesAsync(Stream fileContent, string fileName, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (fileContent == null) { throw new ValidationException(ValidationRules.CannotBeNull, "fileContent"); } if (fileName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "fileName"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("fileContent", fileContent); tracingParameters.Add("fileName", fileName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "UploadFile", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "formdata/stream/uploadfile").ToString(); // 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 (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"); FileStream _fileContentAsFileStream = fileContent as 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) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, 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 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, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } 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 <Stream>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _result.Body = await _httpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
private IHttpResult RequestAccessToken(IServiceBase authService, IAuthSession session, string code, IAuthTokens tokens) { try { //JsonObject json = new JsonObject(); //json["grant_type"] = "authorization_code"; //json["client_id"] = ClientId; //json["scope"] = Scopes.Join(" ").UrlEncode(); //json["code"] = code; //json["redirect_uri"] = CallbackUrl.UrlEncode(); //json["client_secret"] = ClientSecret; // using (var handler = new HttpClientHandler { Proxy = new WebProxy("127.0.0.1:8888", false) }) // { var content = new System.Net.Http.MultipartFormDataContent(); content.Add(new System.Net.Http.StringContent("authorization_code"), "grant_type"); content.Add(new System.Net.Http.StringContent(ClientId), "client_id"); content.Add(new System.Net.Http.StringContent("openid"), "scope"); content.Add(new System.Net.Http.StringContent(code), "id_token"); content.Add(new System.Net.Http.StringContent(CallbackUrl), "redirect_uri"); content.Add(new System.Net.Http.StringContent(ClientSecret), "client_secret"); HttpClient httpClient = new HttpClient(); HttpResponseMessage response = null; string responseJson = null; // run some async code inside a non-async method Task.Run(async() => { response = await httpClient.PostAsync(AccessTokenUrl, content); responseJson = await response.Content.ReadAsStringAsync(); }).GetAwaiter().GetResult(); // tokens. = authInfo["access_token"]; // var formData = "client_id={0}&redirect_uri={1}&client_secret={2}&code={3}&grant_type=authorization_code&resource={4}&scope={5}" // .Fmt(ClientId.UrlEncode(), CallbackUrl.UrlEncode(), ClientSecret.UrlEncode(), code, ResourceId.UrlEncode(), Scopes.Join(" ")); // Endpoint only accepts posts requests // var contents = AccessTokenUrl.PostToUrl(formData); // var contents = AccessTokenUrl.PostJsonToUrl(json.ToString()); // 4. The Azure AD token issuance endpoint returns an access token // and a refresh token. The refresh token can be used to request // additional access tokens. // Response is JSON var authInfo = JsonObject.Parse(responseJson); var authInfoNvc = authInfo.ToNameValueCollection(); if (HasError(authInfoNvc)) { return(RedirectDueToFailure(authService, session, authInfoNvc)); } tokens.AccessTokenSecret = authInfo["access_token"]; tokens.RefreshToken = authInfo["refresh_token"]; tokens.AccessToken = authInfo["id_token"]; return(OnAuthenticated(authService, session, tokens, authInfo.ToDictionary()) ?? authService.Redirect(SuccessRedirectUrlFilter(this, session.ReferrerUrl.SetParam("s", "1")))); //Haz Access! //} } catch (WebException webException) { if (webException.Response == null) { // This could happen e.g. due to a timeout return(RedirectDueToFailure(authService, session, new NameValueCollection { { "error", webException.GetType().ToString() }, { "error_description", webException.Message } })); } Log.Error("Auth Failure", webException); var response = ((HttpWebResponse)webException.Response); var responseText = Encoding.UTF8.GetString( response.GetResponseStream().ReadFully()); var errorInfo = JsonObject.Parse(responseText).ToNameValueCollection(); return(RedirectDueToFailure(authService, session, errorInfo)); } //return RedirectDueToFailure(authService, session, new NameValueCollection()); }
/// <summary>Upload a new Job</summary> /// <param name="file">Input File</param> /// <param name="fScriptParams">Parameters for the script</param> /// <param name="scriptFilename">Script to use</param> /// <param name="outputFileFormat">format of the file output</param> /// <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 { } }
/// <summary>Download converted file from the job</summary> /// <param name="filename">Filename</param> /// <param name="jobId">Job Id</param> /// <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 <FileResponse> DownloadJobFileResultAsync(string filename, string jobId, System.Threading.CancellationToken cancellationToken) { 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_); 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 { } }
public async Task PostProcessing_ProcessesFormData() { // Arrange int maxContents = 16; string contentFormat = "Content {0}"; string formNameFormat = "FormName_{0}"; string fileNameFormat = "FileName_{0}"; MultipartFormDataContent multipartContent = new MultipartFormDataContent(); // Create half contents for form data and the other half for file data. for (int index = 0; index < maxContents; index++) { string content = String.Format(contentFormat, index); string formName = String.Format(formNameFormat, index); if (index < maxContents / 2) { multipartContent.Add(new StringContent(content), formName); } else { string fileName = String.Format(fileNameFormat, index); multipartContent.Add(new StringContent(content), formName, fileName); } } CustomMultipartFormDataRemoteStreamProvider provider = new CustomMultipartFormDataRemoteStreamProvider(); foreach (HttpContent content in multipartContent) { provider.Contents.Add(content); using (provider.GetStream(multipartContent, content.Headers)) { } } // Act await provider.ExecutePostProcessingAsync(); // Assert Assert.Equal(maxContents / 2, provider.FormData.Count); // half contents for form data for (int index = 0; index < maxContents / 2; index++) { string content = String.Format(contentFormat, index); string formName = String.Format(formNameFormat, index); Assert.Equal(content, provider.FormData[formName]); } // the other half for file data HttpContent[] contents = multipartContent.ToArray(); for (int index = maxContents / 2; index < maxContents; index++) { int fileDataIndex = index - (maxContents / 2); string fileName = String.Format(fileNameFormat, index); string url = provider.UrlBase + fileName; Assert.Equal(url, provider.FileData[fileDataIndex].Location); Assert.Same(contents[index].Headers, provider.FileData[fileDataIndex].Headers); } }
//TODO: Update response object public static async Task<Upload> media_upload(this Api api, string media_data = "", byte[] media = null, IEnumerable<string> additional_owners = null) { var uri = "https://upload.twitter.com/1.1/media/upload.json"; var client = new HttpClient(new MessageHandler(api.Token)); var request = new HttpRequestMessage(HttpMethod.Post, uri); var content = new MultipartFormDataContent(); if (!string.IsNullOrEmpty(media_data)) content.Add(new StringContent(media_data)); if (media != null) content.Add(new ByteArrayContent(media)); if (additional_owners != null && additional_owners.Any()) { content.Add(new StringContent(string.Join(",", additional_owners))); } request.Content = content; var response = await client.SendAsync(request); var json = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject<Upload>(json); return result; }
public void sendPost() { // Définition des variables qui seront envoyés HttpContent stringContent1 = new StringContent(param1String); // Le contenu du paramètre P1 HttpContent stringContent2 = new StringContent(param2String); // Le contenu du paramètre P2 HttpContent fileStreamContent = new StreamContent(paramFileStream); //HttpContent bytesContent = new ByteArrayContent(paramFileBytes); using (var client = new HttpClient()) using (var formData = new MultipartFormDataContent()) { formData.Add(stringContent1, "P1"); // Le paramètre P1 aura la valeur contenue dans param1String formData.Add(stringContent2, "P2"); // Le parmaètre P2 aura la valeur contenue dans param2String formData.Add(fileStreamContent, "FICHIER", "RETURN.xml"); // formData.Add(bytesContent, "file2", "file2"); try { var response = client.PostAsync(actionUrl, formData).Result; MessageBox.Show(response.ToString()); if (!response.IsSuccessStatusCode) { MessageBox.Show("Erreur de réponse"); } } catch (Exception Error) { MessageBox.Show(Error.Message); } finally { client.CancelPendingRequests(); } } }