public async void HttpPutRequestUpload(String URL, byte[] data, String contentType) { Stream stream = new MemoryStream(data); HttpStreamContent streamContent = new HttpStreamContent(stream.AsInputStream()); streamContent.Headers.TryAppendWithoutValidation("Content-Type", contentType); Uri resourceAddress = null; Uri.TryCreate(URL.Trim(), UriKind.Absolute, out resourceAddress); System.Diagnostics.Debug.WriteLine("@@@@@@@@@@@@@@@ putImage request (address)=>" + resourceAddress); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put, resourceAddress); request.Content = streamContent; HttpClient httpClient = new HttpClient(); HttpResponseMessage response = await httpClient.SendRequestAsync(request); this._statusCode = response.StatusCode; this._response = await response.Content.ReadAsStringAsync(); System.Diagnostics.Debug.WriteLine("@@@@@@@@@@@@@@@ putImage request (response)=>" + response); if (this._statusCode == HttpStatusCode.Ok || this._statusCode == HttpStatusCode.NoContent) { value = true; } else { HandleErrorHttp err = new HandleErrorHttp(); err.popError(this._statusCode, this._response); value = false; } OnRequestFinished(EventArgs.Empty); }
/// <summary> /// Submits the http post request to the specified uri. /// </summary> /// <param name="uri">The uri to which the post request will be issued.</param> /// <param name="requestStream">Optional stream containing data for the request body.</param> /// <param name="requestStreamContentType">The type of that request body data.</param> /// <returns>Task tracking the completion of the POST request</returns> #pragma warning disable 1998 private async Task <Stream> PostAsync( Uri uri, Stream requestStream = null, string requestStreamContentType = null) { HttpStreamContent requestContent = null; IBuffer dataBuffer = null; if (requestStream != null) { requestContent = new HttpStreamContent(requestStream.AsInputStream()); requestContent.Headers.Remove(ContentTypeHeaderName); requestContent.Headers.TryAppendWithoutValidation(ContentTypeHeaderName, requestStreamContentType); } HttpBaseProtocolFilter httpFilter = new HttpBaseProtocolFilter(); httpFilter.AllowUI = false; if (this.deviceConnection.Credentials != null) { httpFilter.ServerCredential = new PasswordCredential(); httpFilter.ServerCredential.UserName = this.deviceConnection.Credentials.UserName; httpFilter.ServerCredential.Password = this.deviceConnection.Credentials.Password; } using (HttpClient client = new HttpClient(httpFilter)) { this.ApplyHttpHeaders(client, HttpMethods.Post); IAsyncOperationWithProgress <HttpResponseMessage, HttpProgress> responseOperation = client.PostAsync(uri, requestContent); TaskAwaiter <HttpResponseMessage> responseAwaiter = responseOperation.GetAwaiter(); while (!responseAwaiter.IsCompleted) { } using (HttpResponseMessage response = responseOperation.GetResults()) { if (!response.IsSuccessStatusCode) { throw new DevicePortalException(response); } if (response.Content != null) { using (IHttpContent messageContent = response.Content) { IAsyncOperationWithProgress <IBuffer, ulong> bufferOperation = messageContent.ReadAsBufferAsync(); while (bufferOperation.Status != AsyncStatus.Completed) { } dataBuffer = bufferOperation.GetResults(); } } } } return((dataBuffer != null) ? dataBuffer.AsStream() : null); }
public async Task <string> postFile(StorageFile file) { var httpClient = new Windows.Web.Http.HttpClient(); var formContent = new HttpMultipartFormDataContent(); var fileContent = new HttpStreamContent(await file.OpenReadAsync()); fileContent.Headers.ContentType = new Windows.Web.Http.Headers.HttpMediaTypeHeaderValue("mp3"); var apiKeyContent = new HttpStringContent(APIKEY); var apiSecretContent = new HttpStringContent(APISECRET); var cloudNameContent = new HttpStringContent(CLOUDNAME); formContent.Add(fileContent, "myFile", file.Name); formContent.Add(apiKeyContent, "apiKey"); formContent.Add(apiSecretContent, "apiSecret"); formContent.Add(cloudNameContent, "cloudName"); var response = await httpClient.PostAsync(new Uri(APIPOSTFILE), formContent); var stringContent = await response.Content.ReadAsStringAsync(); Debug.WriteLine(stringContent); string url = JObject.Parse(stringContent)["url"].ToString(); if (url.Length > 0) { return(url); } return(""); }
public async Task <T> UploadAsync <T>(string path, HttpStreamContent stream, string fileName, Action <HttpException> action = null) { var form = new HttpMultipartFormDataContent(); form.Add(stream, "file", fileName); return(await UploadAsync <T>(path, form, action)); }
/// <summary> /// 修改头像 /// </summary> /// <param name="stream"></param> /// <param name="action"></param> /// <returns></returns> public async Task <User> UploadAvatarAsync(HttpStreamContent stream, Action <HttpException> action = null) { var form = new HttpMultipartFormDataContent(); form.Add(stream, "file", "avatar.png"); return(await http.PostAsync <User>("auth/user/avatar", form, action)); }
/// <summary> /// Flash a compiled firmware to a device /// A return of true only means it was sent to the device, not that flash is successful /// </summary> /// <param name="deviceId">Device ID</param> /// <param name="firmwareStream">Stream of compiled binary</param> /// <param name="filename">Filename of compiled binary</param> /// <returns>Returns true if binary is sent to device</returns> public override async Task <bool> DeviceFlashBinaryAsync(string deviceId, Stream firmwareStream, string filename) { if (deviceId == null) { throw new ArgumentNullException(nameof(deviceId)); } if (firmwareStream == null) { throw new ArgumentNullException(nameof(firmwareStream)); } using (IHttpContent file = new HttpStreamContent(firmwareStream.AsInputStream())) { file.Headers.ContentType = HttpMediaTypeHeaderValue.Parse("application/octet-stream"); var content = new HttpMultipartFormDataContent(); content.Add(new HttpStringContent("binary"), "file_type"); content.Add(file, "file", filename); try { var responseContent = await PutDataAsync($"{ParticleCloud.ParticleApiVersion}/{ParticleCloud.ParticleApiPathDevices}/{deviceId}", content); return(true); } catch { return(false); } } }
/// <summary> /// Flash a compiled firmware to a device /// A return of true only means it was sent to the device, not that flash is successful /// </summary> /// <param name="firmwareStream">Stream of compiled binary</param> /// <param name="filename">Filename of compiled binary</param> /// <returns>Returns true if binary is sent to device</returns> public async Task <bool> FlashBinaryAsync(Stream firmwareStream, string filename) { if (firmwareStream == null) { throw new ArgumentNullException(nameof(firmwareStream)); } State = ParticleDeviceState.Flashing; isFlashing = true; using (IHttpContent file = new HttpStreamContent(firmwareStream.AsInputStream())) { file.Headers.ContentType = HttpMediaTypeHeaderValue.Parse("application/octet-stream"); var content = new HttpMultipartFormDataContent(); content.Add(new HttpStringContent("binary"), "file_type"); content.Add(file, "file", filename); try { onlineEventListenerID = await SubscribeToDeviceEventsWithPrefixAsync(CheckForOnlineEvent); var responseContent = await particleCloud.PutDataAsync($"{ParticleCloud.ParticleApiVersion}/{ParticleCloud.ParticleApiPathDevices}/{Id}", content); isFlashing = false; return(true); } catch { isFlashing = false; State = ParticleDeviceState.Unknown; return(false); } } }
private async void button_Click(object sender, RoutedEventArgs e) { // Capture image from camera CameraCaptureUI captureUI = new CameraCaptureUI(); captureUI.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Jpeg; captureUI.PhotoSettings.CroppedSizeInPixels = new Size(500, 500); StorageFile photo = await captureUI.CaptureFileAsync(CameraCaptureUIMode.Photo); // Setup http content using stream of captured photo IRandomAccessStream stream = await photo.OpenAsync(FileAccessMode.Read); HttpStreamContent streamContent = new HttpStreamContent(stream); streamContent.Headers.ContentType = new Windows.Web.Http.Headers.HttpMediaTypeHeaderValue("application/octet-stream"); // Setup http request using content Uri apiEndPoint = new Uri("https://api.projectoxford.ai/emotion/v1.0/recognize"); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, apiEndPoint); request.Content = streamContent; // Do an asynchronous POST. string apiKey = "1dd1f4e23a5743139399788aa30a7153"; //Replace this with your own Microsoft Cognitive Services Emotion API key from https://www.microsoft.com/cognitive-services/en-us/emotion-api. Please do not use my key. I include it here so you can get up and running quickly HttpClient httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", apiKey); HttpResponseMessage response = await httpClient.SendRequestAsync(request).AsTask(); // Read response string responseContent = await response.Content.ReadAsStringAsync(); // Display response textBlock.Text = responseContent; }
/// <summary> /// POST 上传文件 /// </summary> /// <param name="url">请求相对路径</param> /// <param name="file">发送的file</param> /// <returns>执行成功为异步任务否为null</returns> public async Task <string> file(string url, StorageFile file) { HttpResponseMessage res = null; HttpMultipartFormDataContent form = new HttpMultipartFormDataContent(); IInputStream fileStream = await file.OpenSequentialReadAsync(); HttpStreamContent content = new HttpStreamContent(fileStream); form.Add(content, "file", file.Name); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, new Uri(location + url)); request.Content = form; res = await client.SendRequestAsync(request); if (res.IsSuccessStatusCode) { string result = res.Content.ReadAsStringAsync().GetResults(); return(result); } else { return(""); } }
public async Task <HttpRequestMessage> Create(string uri) { // TODO: ETag support required?? // TODO: choose rational timeout values var request = HttpRequestHelper.CreateHttpWebRequest(uri, false); //request.AllowWriteStreamBuffering = _allowWriteStreamBuffering; if (_etag != null && _etag.Length != 0) { request.Headers["If-match"] = _etag; } await _parent._requestFilter(request); using (Stream inS = new FileStream(_filename, FileMode.Open, FileAccess.Read, FileShare.Read)) { var streamContent = new HttpStreamContent(inS.AsInputStream()); streamContent.Headers.ContentType = HttpMediaTypeHeaderValue.Parse(MimeHelper.GetContentType(Path.GetExtension(_filename))); if (_parent._options != null && _parent._options.SupportsSlug) { request.Headers["Slug"] = Path.GetFileNameWithoutExtension(_filename); } request.Method = new HttpMethod(_method); } return(request); }
/// <summary> /// 上传图片到 smms 网站 /// </summary> /// <exception cref="IOException"></exception> /// <exception cref="COMException">超时</exception> /// <returns></returns> public async Task <Smms> UploadImage() { const string url = "https://sm.ms/api/upload"; var webHttpClient = new HttpClient(); var httpMultipartFormDataContent = new HttpMultipartFormDataContent(); var fileContent = new HttpStreamContent(await StorageFile.OpenAsync(FileAccessMode.Read)); fileContent.Headers.Add("Content-Type", "application/octet-stream"); // 更多 userAgent 请看 win10 uwp 如何让WebView标识win10手机 https://lindexi.gitee.io/post/win10-uwp-%E5%A6%82%E4%BD%95%E8%AE%A9WebView%E6%A0%87%E8%AF%86win10%E6%89%8B%E6%9C%BA.html var userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36"; webHttpClient.DefaultRequestHeaders.UserAgent.ParseAdd(userAgent); httpMultipartFormDataContent.Add(fileContent, "smfile", StorageFile.Name); var response = await webHttpClient.PostAsync(new Uri(url), httpMultipartFormDataContent); var responseString = response.Content.ToString(); Smms smms = JsonConvert.DeserializeObject <Smms>(responseString); return(smms); }
private static async Task <string> ReadRequest(StreamSocket socket) { uint BufferSize = 8192; var httpStreamContent = new HttpStreamContent(socket.InputStream); var stringContent = await httpStreamContent.ReadAsInputStreamAsync(); var request = new StringBuilder(); using (var input = stringContent) { var data = new byte[BufferSize]; var buffer = data.AsBuffer(); var dataRead = BufferSize; while (dataRead == BufferSize) { await input.ReadAsync(buffer, BufferSize, InputStreamOptions.Partial); request.Append(Encoding.UTF8.GetString(data, 0, data.Length)); dataRead = buffer.Length; } } return(request.ToString()); }
public async static Task <CallRet> MultiPost(string url, NameValueCollection formData, string fileName, IWebProxy proxy = null) { string boundary = RandomBoundary(); HttpClient client = new HttpClient(); Stream formDataStream = new MemoryStream(); FileInfo fileInfo = new FileInfo(fileName); using (FileStream fileStream = fileInfo.OpenRead()) { formDataStream = GetPostStream(fileName, formData, boundary); formDataStream.Position = 0; var requestContent = new HttpStreamContent(formDataStream.AsRandomAccessStream()); requestContent.Headers.ContentType = new HttpMediaTypeHeaderValue("multipart/form-data; boundary =" + boundary); requestContent.Headers.ContentLength = (uint)formDataStream.Length; try { var resp = await client.PostAsync(new Uri(url), requestContent); return(await Client.HandleResult(resp)); } catch (Exception e) { Debug.WriteLine(e.ToString()); return(new CallRet(Windows.Web.Http.HttpStatusCode.BadRequest, e)); } } }
public override async void UploadImage() { string url = "https://sm.ms/api/upload"; HttpClient webHttpClient = new HttpClient(); HttpMultipartFormDataContent httpMultipartFormDataContent = new HttpMultipartFormDataContent(); var fileContent = new HttpStreamContent(await File.OpenAsync(FileAccessMode.Read)); fileContent.Headers.Add("Content-Type", "application/octet-stream"); httpMultipartFormDataContent.Add(fileContent, "smfile", File.Name); var str = await webHttpClient.PostAsync(new Uri(url), httpMultipartFormDataContent); ResponseString = str.Content.ToString(); Smms smms = JsonConvert.DeserializeObject <Smms>(ResponseString); if (smms != null) { if (smms.code == "success") { Url = smms.data.url; OnUploaded?.Invoke(this, true); } else { OnUploaded?.Invoke(this, false); } } else { OnUploaded?.Invoke(this, false); } }
public async Task <string> SendAudioToAPIAsync(IRandomAccessStream stream) { string host = @"speech.platform.bing.com"; string contentType = @"audio/wav; codec=""audio/pcm""; samplerate=16000"; using (HttpClient client = new HttpClient()) { // request id is (GUID) string uri = $"{RecognizeUri}?{QueryString}&requestid={Guid.NewGuid().ToString()}"; client.DefaultRequestHeaders.Authorization = new Windows.Web.Http.Headers.HttpCredentialsHeaderValue("Bearer", AccessToken); client.DefaultRequestHeaders.Accept.Add(new Windows.Web.Http.Headers.HttpMediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Accept.Add(new Windows.Web.Http.Headers.HttpMediaTypeWithQualityHeaderValue("text/xml")); client.DefaultRequestHeaders.Host = new Windows.Networking.HostName(host); client.DefaultRequestHeaders.Add("ContentType", contentType); HttpStreamContent streamContent = new HttpStreamContent(stream); var response = await client.PostAsync(new Uri(uri), streamContent); var buffer = await response.Content.ReadAsBufferAsync(); var byteArray = buffer.ToArray(); var responseString = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length); return(responseString); } }
static async Task <string> SubmitBitmapToCloudGetResultLocationAsync( string cloudEndpoint, string cloudApiKey, DeviceOcrResult deviceOcrResult) { string resultLocation = null; // First, encode the software bitmap as a Jpeg... using (var memoryStream = new InMemoryRandomAccessStream()) { var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, memoryStream); encoder.SetSoftwareBitmap(deviceOcrResult.BestOcrSoftwareBitmap); await encoder.FlushAsync(); memoryStream.Seek(0); // Now, send it off to the computer vision API. using (var httpClient = new HttpClient()) using (var httpContent = new HttpStreamContent(memoryStream)) { httpContent.Headers["Content-Type"] = "application/octet-stream"; httpClient.DefaultRequestHeaders[API_SUBSCRIPTION_KEY_HEADER] = cloudApiKey; using (var response = await httpClient.PostAsync(new Uri(cloudEndpoint), httpContent)) { if (response.IsSuccessStatusCode) { resultLocation = response.Headers["Operation-Location"]; } } } } return(resultLocation); }
/// <summary> /// Upload image and get image ID. /// </summary> /// <param name="file">The image file to be uploaded.</param> /// <returns>An awaitable task with progress. Upon finishing, the image ID will be returned.</returns> public static IAsyncOperationWithProgress <ImageUploadResult, double> UploadImageAsync(this StorageFile file) { if (file == null) { throw new ArgumentNullException(nameof(file)); } if (file.FileType != PngExtension) { throw new Exception("Not a png image."); } return(AsyncInfo.Run <ImageUploadResult, double>((token, progress) => Task.Run(async() => { ImageUploadResult rel; var uploadEndpoint = $"{RequestUrlPrefix}/api/FeedbackImage"; var fileSize = (await file.GetBasicPropertiesAsync()).Size; using (var httpClient = new HttpClient()) { // Set default accept. httpClient.DefaultRequestHeaders.Accept.Add(new HttpMediaTypeWithQualityHeaderValue(JsonMimeType)); // Prep file stream. using (var fileRasStream = await file.OpenAsync(FileAccessMode.Read)) using (var fileInputStream = fileRasStream.GetInputStreamAt(0)) using (var fileStreamContent = new HttpStreamContent(fileInputStream)) { fileStreamContent.Headers.ContentType = new HttpMediaTypeHeaderValue(PngMimeType); fileStreamContent.Headers.ContentLength = fileSize; // Send request var uploadTask = httpClient.PostAsync(new Uri(uploadEndpoint), fileStreamContent); uploadTask.Progress += (info, progressInfo) => { progress.Report((double)progressInfo.BytesSent / fileSize); }; // Wait result var result = await uploadTask; if (result.StatusCode == HttpStatusCode.TooManyRequests) { throw new RequestThrottledException(); } // For other scenarios, HTTP 200 is excepted else if (result.StatusCode != HttpStatusCode.Ok) { throw new FeedbackServerErrorException(); } var content = await result.Content.ReadAsStringAsync(); rel = JsonConvert.DeserializeObject <ImageUploadResult>(content); } } return rel; }, token))); }
public async void SendMessage() { // Prepare string msg = SendTextBox.Text; string id = App.MeVM.Me.Id; if (msg == "") { return; } App.ChatVM.ChatMessages.Add(new MessageModel() { Content = msg, Who = C.ME }); SendTextBox.Text = ""; // Send request HttpClient httpClient = new HttpClient(); Dictionary <string, string> parameters = new Dictionary <string, string>(); parameters.Add("key", ApiKey.Key); parameters.Add("info", msg); parameters.Add("userid", id); HttpRequestMessage request = new HttpRequestMessage() { Content = new HttpFormUrlEncodedContent(parameters), Method = HttpMethod.Post, RequestUri = new Uri(C.API_URI, UriKind.Absolute) }; HttpResponseMessage response = await httpClient.SendRequestAsync(request); if (response.IsSuccessStatusCode) { HttpStreamContent responseContent = (HttpStreamContent)response.Content; if (responseContent != null) { JsonObject resJson = JsonObject.Parse(responseContent.ToString()); int code = (int)resJson["code"].GetNumber(); string text = resJson["text"].GetString(); App.ChatVM.ChatMessages.Add(new MessageModel() { Type = code, Content = text, Who = C.GIY }); //switch (code) { // case C.MSG_TYPE_TEXT //} //try { //} catch (JsonError e) { //} } } else { //TODO: Alert } }
//Post请求内容 public HttpStreamContent SetPostContent(string body) { byte[] subData = new byte[body.Length]; MemoryStream stream = new MemoryStream(subData); HttpStreamContent streamContent = new HttpStreamContent(stream.AsInputStream()); return(streamContent); }
private async Task PrepareHttpContextAsync2() { HttpRequestMessage requestMessage = new HttpRequestMessage(); HttpStreamContent content = new HttpStreamContent(_context.Socket.InputStream); await content.BufferAllAsync(); _context.Response.RequestMessage = requestMessage; }
public async void UploadFileAsync(StorageFile file) { var fileContent = await file.OpenAsync(FileAccessMode.Read); HttpStreamContent fileStream = new HttpStreamContent(fileContent); HttpMultipartFormDataContent formData = new HttpMultipartFormDataContent { { fileStream, "file", file.Path } }; var asyncOperation = BoxHttpClient.PostAsync(new Uri(BoxUploadUrl), formData); int index = UploadFileList.AddEntry(file, DateTime.Now, asyncOperation); UploadFileList[index].StartUpload(); }
private async void btnTakeaPhoto_Click(object sender, RoutedEventArgs e) { CameraCaptureUI captureUI = new CameraCaptureUI(); captureUI.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Jpeg; captureUI.PhotoSettings.CroppedSizeInPixels = new Size(200, 200); StorageFile photo = await captureUI.CaptureFileAsync(CameraCaptureUIMode.Photo); if (photo == null) { // User cancelled photo capture return; } string fileName = CreateTimeToFileName(); StorageFolder destinationFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("ProfilePhotoFolder", CreationCollisionOption.OpenIfExists); await photo.CopyAsync(destinationFolder, fileName, NameCollisionOption.ReplaceExisting); IRandomAccessStream stream = await photo.OpenAsync(FileAccessMode.Read); BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream); SoftwareBitmap softwareBitmap = await decoder.GetSoftwareBitmapAsync(); SoftwareBitmap softwareBitmapBGR8 = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); SoftwareBitmapSource bitmapSource = new SoftwareBitmapSource(); await bitmapSource.SetBitmapAsync(softwareBitmapBGR8); imageControl.Source = bitmapSource; HttpStreamContent streamContent = new HttpStreamContent(stream); streamContent.Headers.ContentType = new Windows.Web.Http.Headers.HttpMediaTypeHeaderValue("application/octet-stream"); Uri apiEndPoint = new Uri("https://api.projectoxford.ai/emotion/v1.0/recognize"); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, apiEndPoint); request.Content = streamContent; // Do an asynchronous POST. HttpClient httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", CognitiveApiKey); HttpResponseMessage response = await httpClient.SendRequestAsync(request).AsTask(); // Read response string responseContent = await response.Content.ReadAsStringAsync(); SendMessage(responseContent); await photo.DeleteAsync(); }
// { // public static T Retry<T>(RetryDelegate<T> del) //// Retry delegate with default retry settings. // const int retryIntervalMS = 200; // const int retryCount = 3; // public delegate void RetryDelegate(); // public delegate T RetryDelegate<T>(); // #region Retry Delegate #region REST HTTP Request Helper Methods // Construct and issue a REST request and return the response. public HttpRequestMessage CreateRESTRequest( string method, string resource, string requestBody = null, Dictionary <string, string> headers = null, string ifMatch = "", string md5 = "") { byte[] byteArray = null; var now = DateTime.UtcNow; var uri = new Uri(this.Endpoint + resource); var httpMethod = new HttpMethod(method); var contentLength = 0; var httpClient = new HttpClient(); var request = new HttpRequestMessage(httpMethod, uri); request.Headers.Add("x-ms-date", now.ToString("R", CultureInfo.InvariantCulture)); request.Headers.Add("x-ms-version", "2009-09-19"); // Debug.WriteLine(now.ToString("R", System.Globalization.CultureInfo.InvariantCulture)); if (this.IsTableStorage) { request.Content.Headers.ContentType = new HttpMediaTypeHeaderValue("application/atom+xml"); request.Headers.Add("DataServiceVersion", "1.0;NetFx"); request.Headers.Add("MaxDataServiceVersion", "1.0;NetFx"); } if (headers != null) { foreach (var header in headers) { request.Headers.Add(header.Key, header.Value); } } if (!string.IsNullOrEmpty(requestBody)) { request.Headers.Add("Accept-Charset", "UTF-8"); byteArray = Encoding.UTF8.GetBytes(requestBody); var stream = new MemoryStream(byteArray); var streamContent = stream.AsInputStream(); var content = new HttpStreamContent(streamContent); request.Content = content; contentLength = byteArray.Length; } var authorizationHeader = this.AuthorizationHeader(method, now, request, contentLength, ifMatch, md5); request.Headers.Authorization = authorizationHeader; return(request); }
public async Task <string> HttpPost_Stream(string argURL, Stream stream) { Uri uri = new Uri(argURL); HttpStreamContent streamContent = new HttpStreamContent(stream.AsInputStream()); HttpResponseMessage response = await httpClient.PostAsync(uri, streamContent).AsTask(cts.Token); string responseBody = await response.Content.ReadAsStringAsync().AsTask(cts.Token); return(responseBody); }
/// <summary> /// Uploads the file. /// </summary> /// <param name="uri">The Uri.</param> /// <param name="stream"></param> /// <param name="contentType">The files content type.</param> /// <param name="cts"></param> /// <param name="progress"></param> /// <returns>true on success, false on error</returns> public async Task <HttpResponseMessage> UploadFile(Uri uri, IRandomAccessStream stream, string contentType, CancellationTokenSource cts, IProgress <HttpProgress> progress) { var inputStream = stream.GetInputStreamAt(0); var streamContent = new HttpStreamContent(inputStream); streamContent.Headers["Content-Type"] = contentType; streamContent.Headers["Content-Length"] = stream.Size.ToString(); return(await _client.PutAsync(uri, streamContent).AsTask(cts.Token, progress)); }
private static HttpStreamContent GeneratePostData <K>(HttpRequestMessage request, K postData, ApiKeyCombo apiKey, Serializer serializer) { Stream postStream = new MemoryStream(); string hashedData = null; try { if (postData is Stream) { (postData as Stream).CopyTo(postStream); postStream.Position = 0; } else { serialize(postStream, postData, serializer); postStream.Position = 0; } if (apiKey != null) { // Turn it into bytes byte[] bytes = new byte[postStream.Length]; postStream.Read(bytes, 0, bytes.Length); postStream.Position = 0; //hash the bytes, then hash ApiKey + Bytes hashedData = EncryptionWin.Sha1(bytes); hashedData = EncryptionWin.Sha256(apiKey.ApiKey + hashedData); } } catch { postStream.Dispose(); throw; } HttpStreamContent content = new HttpStreamContent(postStream.AsInputStream()); if (hashedData != null) { request.Headers["HashedData"] = hashedData; } //content.Headers["HashedData"] = hashedData; // If we serialized as JSON if (!(postData is Stream)) { content.Headers.ContentType = new Windows.Web.Http.Headers.HttpMediaTypeHeaderValue("application/json"); } return(content); }
private async Task PrepareHttpContextAsync2() { HttpRequestMessage requestMessage = new HttpRequestMessage(); HttpStreamContent content = new HttpStreamContent(_context.Socket.InputStream); await content.BufferAllAsync(); _context.Response.RequestMessage = requestMessage; }
public static async Task <List <FaceObject> > AnalyzeImageAsync( InMemoryRandomAccessStream imageStream) { imageStream.Seek(0); var httpContent = new HttpStreamContent(imageStream); await httpContent.BufferAllAsync(); return(await httpClient.PostAsync <List <FaceObject> >( "", httpContent, "application/octet-stream")); }
/// <summary> /// 上传文件,不能超过9.9M,超过后,就不适合这种方式。 为防止大量上传的拒绝攻击,应该用套接字接收或BackgroundUploader /// </summary> /// <param name="CS"></param> /// <returns></returns> public async Task <IDictionary <string, object> > LoadHttpForUpLoad(byte[] file) { RE["头部数据"] = null; RE["返回内容"] = null; RE["访问错误"] = null; RE["缓存标记"] = null; try { //定义一个目标url实例 Uri resourceUri; // 检测url是否合法,并创建实例,如果不合法,给出提示 if (!HttpHelp.TryGetUri(url, out resourceUri)) { RE["访问错误"] = "非法地址,访问失败。"; return(RE); } if (file == null || file.Count() < 1) { RE["访问错误"] = "没有需要上传的内容,上传失败。"; return(RE); } //9.9M . 10485759 //uint streamLength = 10485759; MemoryStream ms = new MemoryStream(file); HttpStreamContent streamContent = new HttpStreamContent(ms.AsInputStream()); streamContent.Headers.ContentLength = Convert.ToUInt32(ms.Length); HttpResponseMessage response = await httpClient.PostAsync(resourceUri, streamContent).AsTask(cts.Token); //获取响应的内容 RE["头部数据"] = HttpHelp.SerializeHeaders(response); string neirong = await response.Content.ReadAsStringAsync().AsTask(cts.Token); RE["返回内容"] = neirong; //定义中途取消 cts.Token.ThrowIfCancellationRequested(); } catch (TaskCanceledException) { RE["访问错误"] = "请求被取消。"; } catch (Exception ex) { RE["访问错误"] = "其他意外错误:" + ex.Message; } return(RE); }
/// <summary> /// Calls the specified API with the provided body. /// </summary> /// <typeparam name="T">The type of the data for the HTTP response body (if present).</typeparam> /// <typeparam name="K">The type of the data for the HTTP request body.</typeparam> /// <param name="apiPath">The relative portion of the uri path that specifies the API to call.</param> /// <param name="bodyData">The data to be used for the HTTP request body.</param> /// <param name="payload">The query string portion of the uri path that provides the parameterized data.</param> /// <returns>Task tracking the PUT completion, optional response body.</returns> private async Task <T> Put <T, K>( string apiPath, K bodyData = null, string payload = null) where T : new() where K : class { T data = default(T); Uri uri = Utilities.BuildEndpoint( this.deviceConnection.Connection, apiPath, payload); #if WINDOWS_UWP HttpStreamContent streamContent = null; #else StreamContent streamContent = null; #endif // WINDOWS_UWP if (bodyData != null) { // Serialize the body to a JSON stream DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(K)); Stream stream = new MemoryStream(); serializer.WriteObject(stream, bodyData); stream.Seek(0, SeekOrigin.Begin); #if WINDOWS_UWP streamContent = new HttpStreamContent(stream.AsInputStream()); streamContent.Headers.ContentType = new HttpMediaTypeHeaderValue("application/json"); #else streamContent = new StreamContent(stream); streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); #endif // WINDOWS_UWP } DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(T)); using (Stream dataStream = await this.Put(uri, streamContent)) { if ((dataStream != null) && (dataStream.Length != 0)) { JsonFormatCheck <T>(dataStream); object response = deserializer.ReadObject(dataStream); data = (T)response; } } return(data); }
/// <summary> /// 获取Post请求正文内容 流 /// </summary> /// <param name="requestItem"></param> /// <returns></returns> private async Task <IHttpContent> GetHttpStreamContent(HttpItem requestItem) { IHttpContent result = null; if (requestItem.PostFiles?.Count > 0) { HttpMultipartFormDataContent httpMultipartFormDataContent = new HttpMultipartFormDataContent(); if (!string.IsNullOrWhiteSpace(requestItem.PostData)) { requestItem.SetPostDataCollection(); foreach (var postdata in requestItem.PostDataCollection) { HttpStringContent kvContent = new HttpStringContent(postdata.Value); kvContent.Headers.ContentType = null; kvContent.Headers.ContentLength = null; //将表单添加进MultipartForm httpMultipartFormDataContent.Add(kvContent, postdata.Key); } } foreach (var file in requestItem.PostFiles) { //将byte转换为流 var stream = await BytesToStream(file.Data); HttpStreamContent streamContent = new HttpStreamContent(stream); streamContent.Headers.ContentType = new HttpMediaTypeHeaderValue(file.ContentType); //修改了ContentDisposition没用?Why??? //streamContent.Headers.ContentDisposition = new HttpContentDispositionHeaderValue("form-data") { FileName = file.FileName, Name = file.Name, FileNameStar = file.FileName }; //将表单添加进MultipartForm httpMultipartFormDataContent.Add(streamContent, file.Name, file.FileName); } //返回MultipartForm result = httpMultipartFormDataContent; } else { if (!string.IsNullOrWhiteSpace(requestItem.PostData)) { var stream = await BytesToStream(requestItem.Encoding.GetBytes(requestItem.PostData)); result = new HttpStreamContent(stream); } } return(result); }
public async void UploadFileAsync(StorageFile file) { var fileContent = await file.OpenAsync(FileAccessMode.Read); HttpStreamContent fileStream = new HttpStreamContent(fileContent); HttpMultipartFormDataContent formData = new HttpMultipartFormDataContent { { fileStream, "file", file.Path } }; var asyncOperation = BoxHttpClient.PostAsync(new Uri(BoxUploadUrl), formData); int index = UploadFileList.AddEntry(file, DateTime.Now, asyncOperation); UploadFileList[index].StartUpload(); }
public static async void HttpUserPost(string phone, string name, string content, string picPath,string tag) { HttpClient httpClient = new HttpClient(); try { string posturi = Config.apiUserUpdate; StorageFile file1 = await StorageFile.GetFileFromPathAsync(picPath); IRandomAccessStreamWithContentType stream1 = await file1.OpenReadAsync(); HttpStreamContent streamContent1 = new HttpStreamContent(stream1); HttpStringContent stringContent = new HttpStringContent(content); HttpStringContent stringTitle = new HttpStringContent(phone); HttpStringContent stringName = new HttpStringContent(name); HttpStringContent stringTag = new HttpStringContent(tag); HttpMultipartFormDataContent fileContent = new HttpMultipartFormDataContent(); fileContent.Add(stringContent, "dream"); fileContent.Add(stringTitle, "phone"); fileContent.Add(stringTag, "tag"); fileContent.Add(stringName, "name"); fileContent.Add(streamContent1, "picture", "pic.jpg"); HttpResponseMessage response = await httpClient.PostAsync(new Uri(posturi), fileContent); string responString = await response.Content.ReadAsStringAsync(); if ((int)response.StatusCode == 200) { JsonObject user = JsonObject.Parse(responString); Config.UserName= user.GetNamedString("name"); Config.UserImage = Config.apiFile+ user.GetNamedString("image"); Config.UserPhone= user.GetNamedString("phone"); Config.UserDream = user.GetNamedString("dream"); Config.UserTag = user.GetNamedString("tag"); NavigationHelp.NavigateTo(typeof(Main)); } } catch (Exception ex) { HelpMethods.Msg(ex.Message.ToString()); } }
private async void Start_Click(object sender, RoutedEventArgs e) { Uri resourceAddress; // The value of 'AddressField' is set by the user and is therefore untrusted input. If we can't create a // valid, absolute URI, we'll notify the user about the incorrect input. if (!Helpers.TryGetUri(AddressField.Text, out resourceAddress)) { rootPage.NotifyUser("Invalid URI.", NotifyType.ErrorMessage); return; } Helpers.ScenarioStarted(StartButton, CancelButton, OutputField); rootPage.NotifyUser("In progress", NotifyType.StatusMessage); try { const int contentLength = 1000; Stream stream = GenerateSampleStream(contentLength); HttpStreamContent streamContent = new HttpStreamContent(stream.AsInputStream()); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, resourceAddress); request.Content = streamContent; // Do an asynchronous POST. HttpResponseMessage response = await httpClient.SendRequestAsync(request).AsTask(cts.Token); await Helpers.DisplayTextResultAsync(response, OutputField, cts.Token); rootPage.NotifyUser("Completed", NotifyType.StatusMessage); } catch (TaskCanceledException) { rootPage.NotifyUser("Request canceled.", NotifyType.ErrorMessage); } catch (Exception ex) { rootPage.NotifyUser("Error: " + ex.Message, NotifyType.ErrorMessage); } finally { Helpers.ScenarioCompleted(StartButton, CancelButton); } }
public async Task<CallRet> CallWithBinary(string url, HttpMediaTypeHeaderValue contentType, Stream body, long length) { Debug.WriteLine("Client.PostWithBinary ==> URL: {0} Length:{1}", url, length); try { HttpClient client = new HttpClient(); body.Position = 0; HttpStreamContent streamContent = new HttpStreamContent(body.AsRandomAccessStream()); HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, new Uri(url)); req.Content = streamContent; SetAuth(req,client, body); var resp = await client.SendRequestAsync(req); return await HandleResult(resp); } catch (Exception e) { Debug.WriteLine(e.ToString()); return new CallRet(Windows.Web.Http.HttpStatusCode.BadRequest, e); } }
private async void Start_Click(object sender, RoutedEventArgs e) { Helpers.ScenarioStarted(StartButton, CancelButton, null); ResetFields(); rootPage.NotifyUser("In progress", NotifyType.StatusMessage); try { // 'AddressField' is a disabled text box, so the value is considered trusted input. When enabling the // text box make sure to validate user input (e.g., by catching FormatException as shown in scenario 1). Uri resourceAddress = new Uri(AddressField.Text); const uint streamLength = 100000; HttpStreamContent streamContent = new HttpStreamContent(new SlowInputStream(streamLength)); // If stream length is unknown, the request is chunked transfer encoded. if (!ChunkedRequestToggle.IsOn) { streamContent.Headers.ContentLength = streamLength; } IProgress<HttpProgress> progress = new Progress<HttpProgress>(ProgressHandler); HttpResponseMessage response = await httpClient.PostAsync(resourceAddress, streamContent).AsTask(cts.Token, progress); rootPage.NotifyUser("Completed", NotifyType.StatusMessage); } catch (TaskCanceledException) { rootPage.NotifyUser("Request canceled.", NotifyType.ErrorMessage); } catch (Exception ex) { rootPage.NotifyUser("Error: " + ex.Message, NotifyType.ErrorMessage); } finally { Helpers.ScenarioCompleted(StartButton, CancelButton); } }
private async void Start_Click(object sender, RoutedEventArgs e) { Helpers.ScenarioStarted(StartButton, CancelButton, OutputField); rootPage.NotifyUser("In progress", NotifyType.StatusMessage); try { const int contentLength = 1000; Stream stream = GenerateSampleStream(contentLength); HttpStreamContent streamContent = new HttpStreamContent(stream.AsInputStream()); // 'AddressField' is a disabled text box, so the value is considered trusted input. When enabling the // text box make sure to validate user input (e.g., by catching FormatException as shown in scenario 1). Uri resourceAddress = new Uri(AddressField.Text); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, resourceAddress); request.Content = streamContent; // Do an asynchronous POST. HttpResponseMessage response = await httpClient.SendRequestAsync(request).AsTask(cts.Token); await Helpers.DisplayTextResultAsync(response, OutputField, cts.Token); rootPage.NotifyUser("Completed", NotifyType.StatusMessage); } catch (TaskCanceledException) { rootPage.NotifyUser("Request canceled.", NotifyType.ErrorMessage); } catch (Exception ex) { rootPage.NotifyUser("Error: " + ex.Message, NotifyType.ErrorMessage); } finally { Helpers.ScenarioCompleted(StartButton, CancelButton); } }
public async void GetMultipartFormData() { Encoding encoding = Encoding.UTF8; string teamid = ApplicationData.Current.LocalSettings.Values["currentTeamID"].ToString(); string memberid = (string)ApplicationData.Current.LocalSettings.Values["currentMemberIDforLoggedInUser"].ToString(); string boundaryGuid = String.Format("{0}",(Guid.NewGuid())); string formDataBoundary = String.Format("----------{0:N}", boundaryGuid); string contentType = "multipart/form-data; boundary=" + formDataBoundary; Stream formDataStream = new System.IO.MemoryStream(); string postData = String.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\nContent-Length: {3}\r\n\r\n{2}", formDataBoundary, "team_id", teamid, teamid.Length); formDataStream.Write(encoding.GetBytes(postData), 0, encoding.GetByteCount(postData)); //Skipped CLRF before first parameter. Adding it before every subsequent parameter //Add member id formDataStream.Write(encoding.GetBytes("\r\n"), 0, encoding.GetByteCount("\r\n")); postData = String.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\nContent-Length: {3}\r\n\r\n{2}", formDataBoundary, "member_id", memberid, memberid.Length); formDataStream.Write(encoding.GetBytes(postData), 0, encoding.GetByteCount(postData)); //Add media_format formDataStream.Write(encoding.GetBytes("\r\n"), 0, encoding.GetByteCount("\r\n")); postData = String.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\nContent-Length: {3}\r\n\r\n{2}", formDataBoundary, "media_format", "image", "5"); formDataStream.Write(encoding.GetBytes(postData), 0, encoding.GetByteCount(postData)); //Add team_media_group_id formDataStream.Write(encoding.GetBytes("\r\n"), 0, encoding.GetByteCount("\r\n")); postData = String.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\nContent-Length: {3}\r\n\r\n{2}", formDataBoundary, "team_media_group_id", team_media_group_id, team_media_group_id.Length); formDataStream.Write(encoding.GetBytes(postData), 0, encoding.GetByteCount(postData)); //Add description formDataStream.Write(encoding.GetBytes("\r\n"), 0, encoding.GetByteCount("\r\n")); postData = String.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\nContent-Length: {3}\r\n\r\n{2}", formDataBoundary, "description", "TesUpload", "9"); formDataStream.Write(encoding.GetBytes(postData), 0, encoding.GetByteCount(postData)); //Add position formDataStream.Write(encoding.GetBytes("\r\n"), 0, encoding.GetByteCount("\r\n")); postData = String.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\nContent-Length: {3}\r\n\r\n{2}", formDataBoundary, "position", upload_position.ToString(), (upload_position.ToString()).Length); formDataStream.Write(encoding.GetBytes(postData), 0, encoding.GetByteCount(postData)); Windows.Storage.StorageFolder storagefolder = Windows.Storage.ApplicationData.Current.LocalFolder; StorageFile samplefile = await storagefolder.GetFileAsync("15381313755274731499.jpg"); var streamfs = await samplefile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite); byte[] data = new byte[streamfs.Size]; var reader = new DataReader(streamfs.GetInputStreamAt(0)); await reader.LoadAsync((uint)streamfs.Size); reader.ReadBytes(data); //FileStream fs = new FileStream("ms-appx:///assets/logo.png", FileMode.Open, FileAccess.Read); //byte[] data = new byte[fs.Length]; //fs.Read(data, 0, data.Length); //fs.Flush(); //fs.Dispose(); //Add image string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\nContent-Length: {4}\r\n\r\n", formDataBoundary, "file", "TesUpload", "image/jpeg", data.Length); formDataStream.Write(encoding.GetBytes(header), 0, encoding.GetByteCount(header)); formDataStream.Write(data, 0, data.Length); string footer = "\r\n--" + formDataBoundary + "--\r\n"; formDataStream.Write(encoding.GetBytes(footer), 0, encoding.GetByteCount(footer)); formDataStream.Position = 0; byte[] formData = new byte[formDataStream.Length]; formDataStream.Read(formData, 0, formData.Length); formDataStream.Flush(); formDataStream.Dispose(); Stream stream = new MemoryStream(formData); HttpStreamContent streamcontent = new HttpStreamContent(stream.AsInputStream()); Windows.Web.Http.HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, new Uri("https://api.teamsnap.com/v3/team_media/upload_team_medium")); req.Content = streamcontent; string access_token = (string)ApplicationData.Current.LocalSettings.Values["Tokens"]; req.Headers.Add("X-TEAMSNAP-ACCESS-TOKEN", access_token); string user_agent = Uri.EscapeDataString("TeamSnap Android 5.1 22 motorola MotoE2(4G-LTE)"); req.Headers.Add("User-Agent", user_agent); // req.Content.Headers.Add("X-TEAMSNAP-ACCESS-TOKEN", access_token); req.Content.Headers.ContentType = new Windows.Web.Http.Headers.HttpMediaTypeHeaderValue("multipart/form-data; boundary=" + boundaryGuid); var httpClient = new HttpClient(); Debug.WriteLine("Team ID : " + teamid); Debug.WriteLine("member ID : " + memberid); Debug.WriteLine("Folder ID : " + team_media_group_id); httpClient.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("Bearer", access_token); try { await httpClient.SendRequestAsync(req); } catch (Exception ex) { } //HttpRequestMessage areq = new HttpRequestMessage(HttpMethod.Post, new Uri("https://api.teamsnap.com/v3/team_media/upload_team_medium")); //Stream stream = new MemoryStream(formData); ////HttpContent metaContent = new HttpStreamContent(stream.AsInputStream()); //areq.Content = new HttpStreamContent(stream.AsInputStream()); ; //POSTing to API //System.Net.HttpWebRequest request = System.Net.WebRequest.Create("https://api.teamsnap.com/v3/team_media/upload_team_medium") as System.Net.HttpWebRequest; //request.Method = "POST"; //request.ContentType = "multipart/form-data; boundary=" + boundaryGuid; }
public async Task<string> upload(string uri, string fileuri) { HttpClient httpClient = new HttpClient(); StorageFile file1 = await StorageFile.GetFileFromApplicationUriAsync(new Uri(fileuri, UriKind.Absolute)); //StorageFile file1 = await StorageFile.; using (IRandomAccessStreamWithContentType stream1 = await file1.OpenReadAsync()) { HttpStreamContent streamContent1 = new HttpStreamContent(stream1); streamContent1.Headers.ContentType = new Windows.Web.Http.Headers.HttpMediaTypeHeaderValue("image/jpeg"); //Stream stream = new System.IO.MemoryStream(image); //long length = stream.Length; //HttpStreamContent streamContent = new HttpStreamContent(stream.AsInputStream()); //HttpStreamContent streamContent = new HttpStreamContent(image.AsInputStream()); //HttpStringContent stringContent = new HttpStringContent("file=", Windows.Storage.Streams.UnicodeEncoding.Utf8, "multipart/form-data"); // streamContent.Headers.ContentType =new Windows.Web.Http.Headers.HttpMediaTypeHeaderValue("image/jpeg"); //streamContent.Headers.ContentLength = (ulong)image.Length; ulong length2; var ll=streamContent1.TryComputeLength(out length2); if (ll == true) { streamContent1.Headers.ContentLength = length2; } System.Diagnostics.Debug.WriteLine(streamContent1.Headers.ContentLength); HttpMultipartFormDataContent hmfdc = new HttpMultipartFormDataContent(); //HttpMultipartContent hmc = new HttpMultipartContent(); //hmfdc.Headers.ContentType = new Windows.Web.Http.Headers.HttpMediaTypeHeaderValue("image/jpeg"); hmfdc.Add(streamContent1, "file", "file1.jpg"); //hmfdc.Add(streamContent, "file", filename); //hmc.Add(streamContent); //hmfdc.Add(stringContent); HttpResponseMessage response = await httpClient.PostAsync(new Uri(uri), hmfdc).AsTask(cts.Token); string responseBody = await response.Content.ReadAsStringAsync().AsTask(cts.Token); System.Diagnostics.Debug.WriteLine(responseBody); return responseBody; } }
public async Task<string> UploadImage2(byte[] image, string url) { Stream stream = new System.IO.MemoryStream(image); HttpStreamContent streamContent = new HttpStreamContent(stream.AsInputStream()); Uri resourceAddress = null; Uri.TryCreate(url.Trim(), UriKind.Absolute, out resourceAddress); Windows.Web.Http.HttpRequestMessage request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, resourceAddress); request.Content = streamContent; var httpClient = new Windows.Web.Http.HttpClient(); var cts = new CancellationTokenSource(); Windows.Web.Http.HttpResponseMessage response = await httpClient.SendRequestAsync(request).AsTask(cts.Token); response.EnsureSuccessStatusCode(); string result =await response.Content.ReadAsStringAsync(); return result; }
public XPRequestParam SetStreamBody(IInputStream body) { Body = new HttpStreamContent(body); return this; }
private async Task TakePhoto() { HttpClient httpClient; var filter = new HttpBaseProtocolFilter(); httpClient = new HttpClient(filter); var cts = new CancellationTokenSource(); var pstream = new InMemoryRandomAccessStream(); await MyMediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), pstream); var decoder = await BitmapDecoder.CreateAsync(pstream); var ffile = await KnownFolders.PicturesLibrary.CreateFileAsync("webcam.jpg", CreationCollisionOption.GenerateUniqueName); using (var outputStream = await ffile.OpenAsync(FileAccessMode.ReadWrite)) { var encoder = await BitmapEncoder.CreateForTranscodingAsync(outputStream, decoder); await encoder.FlushAsync(); } IRandomAccessStream fileStream = await ffile.OpenAsync(FileAccessMode.Read); Stream stream = fileStream.AsStream(); HttpStreamContent streamContent = new HttpStreamContent(stream.AsInputStream()); streamContent.Headers.ContentType = HttpMediaTypeHeaderValue.Parse("image/jpeg"); var content = new HttpMultipartFormDataContent(); content.Add(streamContent, "image", "webcam.jpg"); string POSTuri = "http://peweb.azurewebsites.net/api/PhotoUpload.ashx"; HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, new Uri(POSTuri)); request.Content = content; // Do an asynchronous POST. HttpResponseMessage response = await httpClient.SendRequestAsync(request).AsTask(cts.Token); }
//发送录音 private async void accept_Tapped(object sender, TappedRoutedEventArgs e) { HttpClient httpClient = new HttpClient(); IRandomAccessStreamWithContentType stream1 = await _recordStorageFile.OpenReadAsync(); HttpStreamContent streamContent1 = new HttpStreamContent(stream1); HttpMultipartFormDataContent fileContent = new HttpMultipartFormDataContent(); fileContent.Add(streamContent1, "song", _recordStorageFile.Name); string uri = Config.apiChatRecord; HttpResponseMessage response = await httpClient.PostAsync(new Uri(uri), fileContent); string msgRecord= await response.Content.ReadAsStringAsync(); MessageModel message = new MessageModel(); message.myImage = Config.UserImage; message.myPhone = Config.UserPhone; message.myName = Config.UserName; message.myDream = Config.UserDream; message.type = 1; message.msg = msgRecord; message.toPhone = User.uid; message.toImage = User.image; message.time = HelpMethods.GetTimeNow(); messageList.Add(message); if (myChat.Items.Count > 0) { myChat.ScrollIntoView(myChat.Items.Last(), ScrollIntoViewAlignment.Leading); } string messageJSON = JsonConvert.SerializeObject(message); SocKetHelp.socket.Emit("chat", messageJSON); DbService.Current.Add(message); gridRecord.Visibility = Visibility.Collapsed; record.IsTapEnabled = true; myChat.Visibility = Visibility.Visible; stop.Visibility = Visibility.Visible; cancel.Visibility = Visibility.Collapsed; accept.Visibility = Visibility.Collapsed; if (_mediaCaptureManager != null) { _mediaCaptureManager.Dispose(); _mediaCaptureManager = null; } }
public HttpRequestMessage CreateStreamRESTRequest( string method, string resource, MemoryStream requestBody = null, Dictionary<string, string> headers = null, string ifMatch = "", string md5 = "") { var now = DateTime.UtcNow; var uri = new Uri(this.Endpoint + resource); var httpMethod = new HttpMethod(method); long contentLength = 0; var httpClient = new HttpClient(); var request = new HttpRequestMessage(httpMethod, uri); request.Headers.Add("x-ms-date", now.ToString("R", CultureInfo.InvariantCulture)); request.Headers.Add("x-ms-version", "2009-09-19"); // Debug.WriteLine(now.ToString("R", System.Globalization.CultureInfo.InvariantCulture)); if (this.IsTableStorage) { request.Content.Headers.ContentType = new HttpMediaTypeHeaderValue("application/atom+xml"); request.Headers.Add("DataServiceVersion", "1.0;NetFx"); request.Headers.Add("MaxDataServiceVersion", "1.0;NetFx"); } if (null != headers) { foreach (var header in headers) { request.Headers.Add(header.Key, header.Value); } } if (null != requestBody) { request.Headers.Add("Accept-Charset", "UTF-8"); var streamContent = requestBody.AsInputStream(); var content = new HttpStreamContent(streamContent); request.Content = content; contentLength = requestBody.Length; } var authorizationHeader = this.AuthorizationHeader(method, now, request, contentLength, ifMatch, md5); request.Headers.Authorization = authorizationHeader; return request; }
private async Task PrepareHttpContextAsync() { HttpRequestMessage requestMessage = new HttpRequestMessage(); //IHttpContent requestContent; // TODO: Find better way to handle this read //string request = await ReadRequest(_context.Socket); HttpStreamContent content = new HttpStreamContent(_context.Socket.InputStream); await content.BufferAllAsync(); string request = await content.ReadAsStringAsync(); //string request; //ulong contentLength; //using (IInputStream input = _context.Socket.InputStream) //{ // HttpStreamContent content = new HttpStreamContent(input); // request = await content.ReadAsStringAsync(); //} if (string.IsNullOrWhiteSpace(request)) { return; } string[] requestParts = request.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); //set method var requestLine = requestParts[0].Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); switch (requestLine.Length > 0 ? requestLine[0] : null) { case "OPTIONS": requestMessage.Method = HttpMethod.Options; break; case "GET": requestMessage.Method = HttpMethod.Get; break; case "HEAD": requestMessage.Method = HttpMethod.Head; break; case "POST": requestMessage.Method = HttpMethod.Post; break; case "PUT": requestMessage.Method = HttpMethod.Put; break; case "DELETE": requestMessage.Method = HttpMethod.Delete; break; case "PATCH": requestMessage.Method = HttpMethod.Patch; break; default: break; } //set URL var uri = new Uri(requestLine[1], UriKind.RelativeOrAbsolute); if (!uri.IsAbsoluteUri) uri = new Uri(new Uri($"http://{_context.Socket.Information.LocalAddress}:{_context.Socket.Information.LocalPort}"), uri); if (uri.IsWellFormedOriginalString()) { requestMessage.RequestUri = uri; _context.RouteUri = uri; } else { return; } // set version switch (requestLine[2]) { case "HTTP/1.0": _context.Response.Version = HttpVersion.Http10; break; case "HTTP/1.1": _context.Response.Version = HttpVersion.Http11; break; case "HTTP/2.0": _context.Response.Version = HttpVersion.Http20; break; default: _context.Response.Version = HttpVersion.None; break; } // parse headers for (int i = 1; i < requestParts.Count(); i++) { var line = requestParts[i]; if (string.IsNullOrWhiteSpace(line)) break; var header = line.Split(new[] { ':' }, 2, StringSplitOptions.RemoveEmptyEntries); var headerName = header.Length > 0 ? header[0].Trim() : null; var headerValue = header.Length > 1 ? header[1].Trim() : null; if (headerName != null && headerValue != null) { //Debug.WriteLine("{0}:{1}", headerName, headerValue); switch (headerName.Trim().ToUpper()) { //case "HOST": // requestMessage.Headers.Host = new HostName(headerName.TrimStart('/').TrimEnd(':')); // break; //case "CONTENT-TYPE": // HttpMediaTypeHeaderValue contentType; // if (HttpMediaTypeHeaderValue.TryParse(headerValue, out contentType)) // requestContent.Headers.ContentType = contentType; // break; //case "CONTENT-LENGTH": // if (ulong.TryParse(headerValue, out contentLength)) // requestContent.Headers.ContentLength = contentLength; // break; //case "CONTENT-RANGE": // HttpContentRangeHeaderValue contentRange; // if (HttpContentRangeHeaderValue.TryParse(headerValue, out contentRange)) // requestContent.Headers.ContentRange = contentRange; // break; //case "CONTENT-DISPOSITION": // HttpContentDispositionHeaderValue contentDisposition; // if (HttpContentDispositionHeaderValue.TryParse(headerValue, out contentDisposition)) // requestContent.Headers.ContentDisposition = contentDisposition; // break; //case "CONTENT-LOCATION": // Uri contentLocation; // if (Uri.TryCreate(headerValue, UriKind.RelativeOrAbsolute, out contentLocation)) // requestMessage.Content.Headers.ContentLocation = contentLocation; // break; //case "CONTENT-MD5": // //IBuffer contentMD5 = headerValue; // //requestMessage.Content.Headers.ContentMD5 = contentMD5; // break; //case "CONTENT-LASTMODIFIED": // DateTimeOffset lastModified; // if (DateTimeOffset.TryParse(headerValue, out lastModified)) // requestContent.Headers.LastModified = lastModified; // break; //case "CONTENT-EXPIRES": // DateTimeOffset expires; // if (DateTimeOffset.TryParse(headerValue, out expires)) // requestContent.Headers.Expires = expires; // break; case "COOKIE": HttpCookiePairHeaderValue cookie; if (HttpCookiePairHeaderValue.TryParse(headerValue, out cookie)) requestMessage.Headers.Cookie.Add(cookie); break; default: requestMessage.Headers.Add(headerName, headerValue); break; } } requestMessage.Content = new HttpStringContent(requestParts[requestParts.Count() - 1].ToString()); await requestMessage.Content.BufferAllAsync(); } _context.Response.RequestMessage = requestMessage; }
private async Task SendFileAsync(String url, StorageFile sFile, HttpMethod httpMethod) { //Log data for upload attempt Windows.Storage.FileProperties.BasicProperties fileProperties = await sFile.GetBasicPropertiesAsync(); Dictionary<string, string> properties = new Dictionary<string, string> { { "File Size", fileProperties.Size.ToString() } }; App.Controller.TelemetryClient.TrackEvent("OneDrive picture upload attempt", properties); HttpStreamContent streamContent = null; try { //Open file to send as stream Stream stream = await sFile.OpenStreamForReadAsync(); streamContent = new HttpStreamContent(stream.AsInputStream()); Debug.WriteLine("SendFileAsync() - sending: " + sFile.Path); } catch (FileNotFoundException ex) { Debug.WriteLine(ex.Message); // Log telemetry event about this exception var events = new Dictionary<string, string> { { "OneDrive", ex.Message } }; App.Controller.TelemetryClient.TrackEvent("FailedToOpenFile", events); } catch (Exception ex) { // Log telemetry event about this exception var events = new Dictionary<string, string> { { "OneDrive", ex.Message } }; App.Controller.TelemetryClient.TrackEvent("FailedToOpenFile", events); throw new Exception("SendFileAsync() - Cannot open file. Err= " + ex.Message); } if (streamContent == null) { //Throw exception if stream is not created Debug.WriteLine(" File Path = " + (sFile != null ? sFile.Path : "?")); throw new Exception("SendFileAsync() - Cannot open file."); } try { Uri resourceAddress = new Uri(url); //Create requst to upload file using (HttpRequestMessage request = new HttpRequestMessage(httpMethod, resourceAddress)) { request.Content = streamContent; // Do an asynchronous POST. using (HttpResponseMessage response = await httpClient.SendRequestAsync(request).AsTask(cts.Token)) { await DebugTextResultAsync(response); if (response.StatusCode != HttpStatusCode.Created) { throw new Exception("SendFileAsync() - " + response.StatusCode); } } } } catch (TaskCanceledException ex) { // Log telemetry event about this exception var events = new Dictionary<string, string> { { "OneDrive", ex.Message } }; App.Controller.TelemetryClient.TrackEvent("CancelledFileUpload", events); throw new Exception("SendFileAsync() - " + ex.Message); } catch (Exception ex) { // This failure will already be logged in telemetry in the enclosing UploadPictures function. We don't want this to be recorded twice. throw new Exception("SendFileAsync() - Error: " + ex.Message); } finally { streamContent.Dispose(); Debug.WriteLine("SendFileAsync() - final."); } App.Controller.TelemetryClient.TrackEvent("OneDrive picture upload success", properties); }
public async static Task<CallRet> MultiPost(string url, NameValueCollection formData, string fileName, IWebProxy proxy = null) { string boundary = RandomBoundary(); HttpClient client = new HttpClient(); Stream formDataStream = new MemoryStream(); FileInfo fileInfo = new FileInfo(fileName); using (FileStream fileStream = fileInfo.OpenRead()) { formDataStream = GetPostStream(fileName, formData, boundary); formDataStream.Position = 0; var requestContent = new HttpStreamContent(formDataStream.AsRandomAccessStream()); requestContent.Headers.ContentType = new HttpMediaTypeHeaderValue("multipart/form-data; boundary =" +boundary); requestContent.Headers.ContentLength = (uint)formDataStream.Length; try { var resp = await client.PostAsync(new Uri(url), requestContent); return await Client.HandleResult(resp); } catch (Exception e) { Debug.WriteLine(e.ToString()); return new CallRet(Windows.Web.Http.HttpStatusCode.BadRequest, e); } } }
private static async Task<string> ReadRequest(StreamSocket socket) { uint BufferSize = 8192; var httpStreamContent = new HttpStreamContent(socket.InputStream); var stringContent = await httpStreamContent.ReadAsInputStreamAsync(); var request = new StringBuilder(); using (var input = stringContent) { var data = new byte[BufferSize]; var buffer = data.AsBuffer(); var dataRead = BufferSize; while (dataRead == BufferSize) { await input.ReadAsync(buffer, BufferSize, InputStreamOptions.Partial); request.Append(Encoding.UTF8.GetString(data, 0, data.Length)); dataRead = buffer.Length; } } return request.ToString(); }
private async Task UploadImages(HttpStreamContent streamContent) { try { string posturi = "https://upload.api.weibo.com/2/statuses/upload_pic.json?access_token=" + App.WeicoAccessToken; HttpClient httpClient = new HttpClient(); HttpMultipartFormDataContent fileContent = new HttpMultipartFormDataContent(); fileContent.Add(streamContent, "pic", "pic.jpg"); HttpResponseMessage response = await httpClient.PostAsync(new Uri(posturi), fileContent); string a = await response.Content.ReadAsStringAsync(); JObject o = JObject.Parse(a); pic_ids += (string)o["pic_id"]; pic_ids += ","; } catch (Exception e) { Debug.WriteLine(e.ToString()); } }
private async Task PostNewWeibo(string textBlockString) { try { if (files != null) { string posturi = "https://api.weibo.com/2/statuses/upload_url_text.json?access_token=" + App.WeicoAccessToken; foreach (StorageFile file in SendOut) { FileRandomAccessStream stream = (FileRandomAccessStream)await file.OpenAsync(FileAccessMode.Read); HttpStreamContent streamContent1 = new HttpStreamContent(stream); await UploadImages(streamContent1); } HttpClient httpClient = new HttpClient(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, new Uri(posturi)); HttpFormUrlEncodedContent postData = new HttpFormUrlEncodedContent( new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("status", textBlockString), new KeyValuePair<string, string>("pic_id", pic_ids), } ); request.Content = postData; HttpResponseMessage response = await httpClient.SendRequestAsync(request); if (response.IsSuccessStatusCode) { ToastService.SendToast("发送成功", 1000); await Task.Delay(600); NavigationService.GoBack(); } else { StatusCodeDetermine(response); } } else { HttpClient httpClient = new HttpClient(); string posturi = "https://api.weibo.com/2/statuses/update.json?"; HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, new Uri(posturi)); HttpFormUrlEncodedContent postData = new HttpFormUrlEncodedContent( new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("access_token",App.AccessToken), new KeyValuePair<string, string>("status", textBlockString), } ); request.Content = postData; HttpResponseMessage response = await httpClient.SendRequestAsync(request); if (response.IsSuccessStatusCode) { ToastService.SendToast("发送成功", 1000); await Task.Delay(600); NavigationService.GoBack(); } else { StatusCodeDetermine(response); } } SendOut.Clear(); } catch(Exception e) { ToastService.SendToast("Network not available", 1000); } }
public static async Task<string> HttpPost(StorageFile inFile) { HttpClient httpClient = new HttpClient(); uint MaxImageWidth = 480; uint MaxImageHeight = 800; uint width; uint height; string posturi = Config.apiChatImage; HttpMultipartFormDataContent fileContent = new HttpMultipartFormDataContent(); var inStream = await inFile.OpenReadAsync(); InMemoryRandomAccessStream outStream = new InMemoryRandomAccessStream(); BitmapDecoder decoder = await ImageHelp.GetProperDecoder(inStream,inFile); if (decoder.OrientedPixelWidth > MaxImageWidth && decoder.OrientedPixelHeight > MaxImageHeight) { width = MaxImageWidth; height = MaxImageHeight; } else { width = decoder.OrientedPixelWidth; height = decoder.OrientedPixelHeight; } PixelDataProvider provider = await decoder.GetPixelDataAsync(); byte[] data = provider.DetachPixelData(); //获取像素数据的字节数组 BitmapPropertySet propertySet = new BitmapPropertySet(); BitmapTypedValue qualityValue = new BitmapTypedValue(0.5, PropertyType.Single); propertySet.Add("ImageQuality", qualityValue); var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, outStream, propertySet);//建立编码器 encoder.SetPixelData(decoder.BitmapPixelFormat, decoder.BitmapAlphaMode, decoder.OrientedPixelWidth, decoder.OrientedPixelHeight, decoder.DpiX, decoder.DpiY, data ); encoder.BitmapTransform.ScaledWidth = width; encoder.BitmapTransform.ScaledHeight = height; await encoder.FlushAsync(); HttpStreamContent streamContent1 = new HttpStreamContent(outStream); fileContent.Add(streamContent1, "pic", inFile.Name); HttpResponseMessage response = await httpClient.PostAsync(new Uri(posturi), fileContent); return await response.Content.ReadAsStringAsync(); }
private async Task<string> headupload() { HttpClient _httpClient = new HttpClient(); CancellationTokenSource _cts = new CancellationTokenSource(); HttpStringContent uidStringContent = new HttpStringContent(appSetting.Values["uid"].ToString()); HttpStringContent tokenStringContent = new HttpStringContent(appSetting.Values["token"].ToString()); string head = ""; IStorageFolder applicationFolder = ApplicationData.Current.LocalFolder; IStorageFile saveFile; try { saveFile = await applicationFolder.GetFileAsync("temphead.png"); } catch (Exception) { } try { saveFile = await applicationFolder.GetFileAsync("head.png"); saveFile.RenameAsync("head.png", NameCollisionOption.ReplaceExisting); // 构造需要上传的文件数据 IRandomAccessStreamWithContentType stream1 = await saveFile.OpenReadAsync(); HttpStreamContent streamContent = new HttpStreamContent(stream1); HttpMultipartFormDataContent fileContent = new HttpMultipartFormDataContent(); fileContent.Add(streamContent, "photo", "head.png"); fileContent.Add(uidStringContent, "uid"); fileContent.Add(tokenStringContent, "token"); HttpResponseMessage response = await _httpClient.PostAsync(new Uri("http://106.184.7.12:8002/index.php/api/person/uploadimg"), fileContent) .AsTask(_cts.Token); head = Utils.ConvertUnicodeStringToChinese(await response.Content.ReadAsStringAsync().AsTask(_cts.Token)); Debug.WriteLine(head); return head; } catch (Exception) { Debug.WriteLine("上传头像失败,编辑页面"); return ""; } }
private async void Start_Click(object sender, RoutedEventArgs e) { Uri resourceAddress; // The value of 'AddressField' is set by the user and is therefore untrusted input. If we can't create a // valid, absolute URI, we'll notify the user about the incorrect input. if (!Helpers.TryGetUri(AddressField.Text, out resourceAddress)) { rootPage.NotifyUser("Invalid URI.", NotifyType.ErrorMessage); return; } Helpers.ScenarioStarted(StartButton, CancelButton, null); ResetFields(); rootPage.NotifyUser("In progress", NotifyType.StatusMessage); try { const uint streamLength = 100000; HttpStreamContent streamContent = new HttpStreamContent(new SlowInputStream(streamLength)); // If stream length is unknown, the request is chunked transfer encoded. if (!ChunkedRequestToggle.IsOn) { streamContent.Headers.ContentLength = streamLength; } IProgress<HttpProgress> progress = new Progress<HttpProgress>(ProgressHandler); HttpResponseMessage response = await httpClient.PostAsync(resourceAddress, streamContent).AsTask(cts.Token, progress); rootPage.NotifyUser("Completed", NotifyType.StatusMessage); } catch (TaskCanceledException) { rootPage.NotifyUser("Request canceled.", NotifyType.ErrorMessage); } catch (Exception ex) { rootPage.NotifyUser("Error: " + ex.Message, NotifyType.ErrorMessage); } finally { RequestProgressBar.Value = 100; Helpers.ScenarioCompleted(StartButton, CancelButton); } }
/// <summary> /// Uploads a file to OneDrive. This method is NOT thread safe. It assumes that the contents of the file will not change during the upload process. /// </summary> /// <param name="file"></param> The file to upload to OneDrive. The file will be read, and a copy uploaded. The original file object will not be modified. /// <param name="destinationPath"></param> The path to the destination on Onedrive. Passing in an empty string will place the file in the root of Onedrive. Other folder paths should be passed in with a leading '/' character, such as "/Documents" or "/Pictures/Random" /// <returns>The response message given by the server for the request</returns> public IAsyncOperation<HttpResponseMessage> UploadFileAsync(StorageFile file, string destinationPath) { string uploadUri = String.Format(UploadUrlFormat, destinationPath, file.Name); return Task.Run(async () => { using (Stream stream = await file.OpenStreamForReadAsync()) { using (HttpStreamContent streamContent = new HttpStreamContent(stream.AsInputStream())) { using (HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Put, new Uri(uploadUri))) { requestMessage.Content = streamContent; using (HttpResponseMessage response = await httpClient.SendRequestAsync(requestMessage)) { return response; } } } } }).AsAsyncOperation<HttpResponseMessage>(); }
// Construct and issue a REST request and return the response. public HttpRequestMessage CreateRESTRequest(string method, string resource, string requestBody = null, Dictionary<string, string> headers = null, string ifMatch = "", string md5 = "") { byte[] byteArray = null; DateTime now = DateTime.UtcNow; Uri uri = new Uri(Endpoint + resource); HttpMethod httpMethod = new HttpMethod(method); int contentLength = 0; var httpClient = new HttpClient(); HttpRequestMessage request = new HttpRequestMessage(httpMethod, uri); request.Headers.Add("x-ms-date", now.ToString("R", System.Globalization.CultureInfo.InvariantCulture)); request.Headers.Add("x-ms-version", "2009-09-19"); //Debug.WriteLine(now.ToString("R", System.Globalization.CultureInfo.InvariantCulture)); if (IsTableStorage) { request.Content.Headers.ContentType = new Windows.Web.Http.Headers.HttpMediaTypeHeaderValue("application/atom+xml"); request.Headers.Add("DataServiceVersion", "1.0;NetFx"); request.Headers.Add("MaxDataServiceVersion", "1.0;NetFx"); } if (headers != null) { foreach (KeyValuePair<string, string> header in headers) { request.Headers.Add(header.Key, header.Value); } } if (!String.IsNullOrEmpty(requestBody)) { request.Headers.Add("Accept-Charset", "UTF-8"); byteArray = Encoding.UTF8.GetBytes(requestBody); MemoryStream stream = new MemoryStream(byteArray); Windows.Storage.Streams.IInputStream streamContent = stream.AsInputStream(); HttpStreamContent content = new HttpStreamContent(streamContent); request.Content = content; contentLength = byteArray.Length; } var authorizationHeader = AuthorizationHeader(method, now, request, contentLength, ifMatch, md5); request.Headers.Authorization = authorizationHeader; return request; }
public async void HttpPost(string uid, string uimage, string name, string content, List<string> imagePsthList, string songPath,string date,int type) { NotifyControl notify = new NotifyControl(); notify.Text = "亲,努力发送中..."; notify.Show(); HttpClient httpClient = new HttpClient(); uint MaxImageWidth = 480; uint MaxImageHeight = 800; uint width; uint height; try { string posturi = Config.apiDreamingPublish; HttpMultipartFormDataContent fileContent = new HttpMultipartFormDataContent(); if (imagePsthList.Count > 0) { for (int i = 0; i < imagePsthList.Count; i++) { StorageFile inFile = await StorageFile.GetFileFromPathAsync(imagePsthList[i]); var inStream = await inFile.OpenReadAsync(); InMemoryRandomAccessStream outStream = new InMemoryRandomAccessStream(); BitmapDecoder decoder = await ImageHelp.GetProperDecoder(inStream,inFile); if (decoder == null) return; if (decoder.OrientedPixelWidth > MaxImageWidth && decoder.OrientedPixelHeight > MaxImageHeight) { width = MaxImageWidth; height = MaxImageHeight; } else { width = decoder.OrientedPixelWidth; height = decoder.OrientedPixelHeight; } PixelDataProvider provider = await decoder.GetPixelDataAsync(); byte[] data = provider.DetachPixelData(); //获取像素数据的字节数组 BitmapPropertySet propertySet = new BitmapPropertySet(); BitmapTypedValue qualityValue = new BitmapTypedValue(0.5, PropertyType.Single); propertySet.Add("ImageQuality", qualityValue); var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, outStream, propertySet);//建立编码器 encoder.SetPixelData(decoder.BitmapPixelFormat, decoder.BitmapAlphaMode, decoder.OrientedPixelWidth, decoder.OrientedPixelHeight, decoder.DpiX, decoder.DpiY, data ); encoder.BitmapTransform.ScaledWidth = width; encoder.BitmapTransform.ScaledHeight = height; await encoder.FlushAsync(); HttpStreamContent streamContent1 = new HttpStreamContent(outStream); fileContent.Add(streamContent1, "pic", inFile.Name); } } if (songPath != null) { StorageFile file1 = await StorageFile.GetFileFromPathAsync(songPath); IRandomAccessStreamWithContentType stream1 = await file1.OpenReadAsync(); HttpStreamContent streamContent1 = new HttpStreamContent(stream1); fileContent.Add(streamContent1, "song", file1.Name); } HttpStringContent stringContent = new HttpStringContent(content); HttpStringContent stringName = new HttpStringContent(name); HttpStringContent stringUid = new HttpStringContent(uid); HttpStringContent stringUimage = new HttpStringContent(uimage); HttpStringContent stringTime = new HttpStringContent(date); HttpStringContent stringType = new HttpStringContent(type.ToString()); fileContent.Add(stringContent, "content"); fileContent.Add(stringUid, "phone"); fileContent.Add(stringUimage, "uimage"); fileContent.Add(stringName, "name"); fileContent.Add(stringTime, "time"); fileContent.Add(stringType, "type"); HttpResponseMessage response = await httpClient.PostAsync(new Uri(posturi), fileContent); Init(); notify.Hide(); PostCommand.CanExecutes = true; NavigationHelp.NavigateTo(typeof(AllDreaming)); } catch (Exception ex) { HelpMethods.Msg(ex.Message.ToString()); } }
public async Task<long> UploadFileAsync( string fileName, Stream fileContent ) { var client = new HttpClient(); foreach ( var pair in _headers.Current ) { client.DefaultRequestHeaders.Add( pair.Key, pair.Value ); } string downloadUrl = _settings.Configuration.ServerBaseUrl + PluginName; var uri = new Uri( downloadUrl, UriKind.Absolute ); var streamContent = new HttpStreamContent( fileContent.AsInputStream() ); var content = new HttpMultipartFormDataContent { { streamContent, FileContentName }, }; // It's important to set this here and not before; // HttpMultipartFormDataContent overwrites the headers of its contents. streamContent.Headers.ContentDisposition.FileName = fileName; var response = await client.PostAsync( uri, content ); if ( response.StatusCode == HttpStatusCode.ProxyAuthenticationRequired ) { throw new AuthenticationRequiredException(); } response.EnsureSuccessStatusCode(); var responseStream = await response.Content.ReadAsInputStreamAsync(); var serializer = new DataContractJsonSerializer( typeof( CloudPrintUploadResponse ) ); var responseObj = (CloudPrintUploadResponse) serializer.ReadObject( responseStream.AsStreamForRead() ); return responseObj.DocumentId; }