Created
August 20, 2017 16:58
-
-
Save voyagerwoo/263c0befa87ec5dcc8c1b82a0ac1bfea to your computer and use it in GitHub Desktop.
UWP httpClient muptipart request - file + json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using Newtonsoft.Json; | |
| using System; | |
| using System.Diagnostics; | |
| using System.IO; | |
| using Windows.Web.Http; | |
| namespace vw.http.service | |
| { | |
| class MultiPartService | |
| { | |
| private HttpClient client = new HttpClient(); | |
| public async void Request(String uri, Stream fileStream, FileInfo fileInfo) | |
| { | |
| HttpMultipartFormDataContent multipartContent = | |
| new HttpMultipartFormDataContent(); | |
| multipartContent.Add( | |
| new HttpStreamContent(fileStream.AsInputStream()), | |
| "file", | |
| fileInfo.Filename); | |
| ; | |
| multipartContent.Add( | |
| new HttpStringContent( | |
| JsonConvert.SerializeObject(fileInfo), | |
| Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json"), | |
| "fileInfo"); | |
| HttpClient client = new HttpClient(); | |
| HttpResponseMessage response = await client.PostAsync( | |
| new Uri(uri), | |
| multipartContent); | |
| if (response.StatusCode != HttpStatusCode.Ok) | |
| throw new BadResponseException(); | |
| string responseBody = await response.Content.ReadAsStringAsync(); | |
| Debug.WriteLine(responseBody); | |
| } | |
| } | |
| class FileInfo | |
| { | |
| public String Filename { get; set; } | |
| public String Author { get; set; } | |
| public Int64 GroupId { get; set; } | |
| public Int64 ExpiredTime { get; set; } | |
| } | |
| class BadResponseException : Exception | |
| { | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment