Ejemplo n.º 1
0
        public virtual async Task <string> Comment(string id, string text)
        {
            string content = null;

            try
            {
                if (client == null)
                {
                    client = new HttpClient();
                }

                string url = App.Settings.current_site + "index.php?page=comment&id=" + id + "&s=save";
                HttpMultipartFormDataContent httpContents = new HttpMultipartFormDataContent();
                httpContents.Add(new HttpStringContent(text), "comment");
                httpContents.Add(new HttpStringContent("Post comment"), "submit");
                httpContents.Add(new HttpStringContent("1"), "conf");

                using (HttpResponseMessage response = await client.PostAsync(new Uri(url), httpContents))
                {
                    if (response.IsSuccessStatusCode)
                    {
                        content = await response.Content.ReadAsStringAsync();
                    }
                }
            }
            catch (Exception)
            {
            }
            return(content);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Performs HTTP POST media byte array upload to Twitter.
        /// </summary>
        /// <param name="url">Url to upload to.</param>
        /// <param name="postData">Request parameters.</param>
        /// <param name="data">Image to upload.</param>
        /// <param name="name">Image parameter name.</param>
        /// <param name="fileName">Image file name.</param>
        /// <param name="contentType">Type of image: must be one of jpg, gif, or png.</param>
        /// <param name="reqProc">Request processor for handling results.</param>
        /// <returns>JSON response From Twitter.</returns>
        public async Task <string> PostImageAsync(string url, IDictionary <string, string> postData, byte[] data, string name, string fileName, string contentType, CancellationToken cancelToken)
        {
            WriteLog(url, nameof(PostImageAsync));

            var multiPartContent = new HttpMultipartFormDataContent();
            var byteArrayContent = new HttpBufferContent(data.AsBuffer());

            byteArrayContent.Headers.Add("Content-Type", contentType);
            multiPartContent.Add(byteArrayContent, name, fileName);

            var cleanPostData = new Dictionary <string, string>();

            foreach (var pair in postData)
            {
                if (pair.Value != null)
                {
                    cleanPostData.Add(pair.Key, pair.Value);
                    multiPartContent.Add(new HttpStringContent(pair.Value), pair.Key);
                }
            }

            var baseFilter = new HttpBaseProtocolFilter
            {
                AutomaticDecompression = Authorizer.SupportsCompression,
                ProxyCredential        = Authorizer.ProxyCredential,
                UseProxy = Authorizer.UseProxy
            };
            var handler = new PostMessageFilter(this, new Dictionary <string, string>(), url, baseFilter, cancelToken);
            var client  = new HttpClient(handler);

            HttpResponseMessage msg = await client.PostAsync(new Uri(url), multiPartContent);

            return(await HandleResponseAsync(msg));
        }
Ejemplo n.º 3
0
        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("");
        }
Ejemplo n.º 4
0
        public static async Task <String> PostAsync(String url, IEnumerable <KeyValuePair <String, String> > parameters, IEnumerable <EntitledStorageFile> content)
        {
            try
            {
                var multipartFormDataContent = new HttpMultipartFormDataContent("----Asrf456BGe4h");
                foreach (var parameter in parameters)
                {
                    multipartFormDataContent.Add(new HttpStringContent(parameter.Value), parameter.Key);
                }

                foreach (var contentFile in content)
                {
                    var stream = await contentFile.File.OpenAsync(FileAccessMode.Read).AsTask().ConfigureAwait(false);

                    multipartFormDataContent.Add(new HttpStreamContent(stream), contentFile.Title, contentFile.File.Name);
                }
                var response        = await new HttpClient().PostAsync(new Uri(url, UriKind.Absolute), multipartFormDataContent).AsTask().ConfigureAwait(false);
                var responseContent = await response.Content.ReadAsStringAsync().AsTask().ConfigureAwait(false);

                if (!response.IsSuccessStatusCode)
                {
                    throw new HttpClientException((Int32)response.StatusCode, responseContent);
                }
                return(responseContent);
            }
            catch (Exception error)
            {
                if (error.HResult == unchecked ((Int32)0x80072EE7))
                {
                    throw new HttpClientException();
                }
                throw;
            }
        }
Ejemplo n.º 5
0
        public static async Task <string> Login(string username, string pwd)
        {
            HttpMultipartFormDataContent form = new HttpMultipartFormDataContent();

            form.Add(new HttpStringContent(username), "username");
            form.Add(new HttpStringContent(pwd), "password");
            string url_login_string      = loader.GetString("URL_BASE_MOBILE_API") + loader.GetString("URL_LOGIN");
            Uri    url_login             = new Uri(url_login_string);
            HttpResponseMessage response = await hc.PostAsync(url_login, form);

            Debug.WriteLine(response.Content);
            Debug.WriteLine(response.Headers);
            HttpBaseProtocolFilter filter           = new HttpBaseProtocolFilter();
            HttpCookieCollection   cookieCollection = filter.CookieManager.GetCookies(response.RequestMessage.RequestUri);
            string result = "";

            result = cookieCollection.Count + " cookies found.\r\n";
            foreach (HttpCookie cookie in cookieCollection)
            {
                result += "--------------------\r\n";
                result += "Name: " + cookie.Name + "\r\n";
                result += "Domain: " + cookie.Domain + "\r\n";
                result += "Path: " + cookie.Path + "\r\n";
                result += "Value: " + cookie.Value + "\r\n";
                result += "Expires: " + cookie.Expires + "\r\n";
                result += "Secure: " + cookie.Secure + "\r\n";
                result += "HttpOnly: " + cookie.HttpOnly + "\r\n";
            }

            return(result);
            //return response.Content + "\n==========\n" + response.Headers.ToString();
        }
Ejemplo n.º 6
0
        /// <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);
                }
            }
        }
Ejemplo n.º 7
0
        /// <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);
                }
            }
        }
Ejemplo n.º 8
0
        protected async static Task <IBuffer> PostAPIBufferPdf(string API, string data, IEnumerable <IBuffer> files)
        {
            cts = new CancellationTokenSource();

            Uri resourceUri = new Uri(AddressField + API);

            rootPage.NotifyUser("En progreso", NotifyType.StatusMessage);

            try
            {
                HttpResponseMessage response;

                do
                {
                    Repetir = false;

                    httpClient = await Helpers.CreateHttpClient(httpClient);

                    HttpMultipartFormDataContent form = new HttpMultipartFormDataContent();

                    form.Add(new HttpStringContent(data), "model");
                    form.First().Headers.ContentType = Windows.Web.Http.Headers.HttpMediaTypeHeaderValue.Parse("application/json");

                    for (int i = 0; i < files.Count(); i++)
                    {
                        form.Add(new HttpBufferContent(files.ElementAt(i), 0, files.ElementAt(i).Length), "image" + i, "Imagen" + i + ".bmp");
                        form.ElementAt(i + 1).Headers.ContentType = Windows.Web.Http.Headers.HttpMediaTypeHeaderValue.Parse("image/bmp");
                    }

                    response = await httpClient.PostAsync(resourceUri, form).AsTask(cts.Token);

                    if (!response.IsSuccessStatusCode)
                    {
                        await MostrarErrorAPI(response);
                    }
                }while (Repetir);

                IBuffer result = await Helpers.GetStreamResultAsync(response, cts.Token);

                rootPage.NotifyUser("Completado.", NotifyType.StatusMessage);

                return(result);
            }
            catch (TaskCanceledException)
            {
                rootPage.NotifyUser("Solicitud cancelada.", NotifyType.ErrorMessage);

                throw;
            }
            catch (Exception ex)
            {
                rootPage.NotifyUser("Error: " + ex.Message, NotifyType.ErrorMessage);

                throw;
            }
        }
Ejemplo n.º 9
0
        private async void SubmitButton_Click(object sender, RoutedEventArgs e)
        {
            try {
                var    localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
                Object value         = localSettings.Values["TBDCServer"];

                if (value == null)
                {
                    localSettings.Values["TBDCServer"] = "N/A";
                    MessageBox.Show("Error: server setting is not set yet!");
                    NavigationService.Navigate(new Uri("/SettingServerPage.xaml", UriKind.Relative));
                    return;
                }
                else
                {
                    server_url = value.ToString() + "/patient/lab_result/store";
                }

                IsolatedStorageFile       isStore      = IsolatedStorageFile.GetUserStoreForApplication();
                IsolatedStorageFileStream targetStream = isStore.OpenFile(file, FileMode.Open, FileAccess.Read);


                IsolatedStorageFile       isolatedStorageFile       = IsolatedStorageFile.GetUserStoreForApplication();
                IsolatedStorageFileStream isolatedStorageFileStream = isolatedStorageFile.OpenFile(file, FileMode.Open, FileAccess.Read);

                HttpMultipartFormDataContent multipartContent = new HttpMultipartFormDataContent();

                multipartContent.Add(new HttpStreamContent(isolatedStorageFileStream.AsInputStream()), "photo", file);
                multipartContent.Add(new HttpStringContent("admin"), "username");
                multipartContent.Add(new HttpStringContent("djangoadmin"), "password");
                multipartContent.Add(new HttpStringContent(patient), "patient_id");

                HttpClient          client   = new HttpClient();
                HttpResponseMessage response = await client.PostAsync(new Uri(server_url), multipartContent);

                String responseStr = await response.Content.ReadAsStringAsync();

                Debug.WriteLine(responseStr);

                if (responseStr.Contains("\"status\": \"success\", \"message\": \"Photo uploaded!\""))
                {
                    if (MessageBox.Show("Sputum has been succesfully assigned to Patient " + patient + " !") == MessageBoxResult.OK)
                    {
                        NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Error: check server settings!");
                NavigationService.Navigate(new Uri("/SettingServerPage.xaml", UriKind.Relative));
                return;
            }
        }
Ejemplo n.º 10
0
 private async void ContentDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
 {
     using (var content = new HttpMultipartFormDataContent())
         using (var type = new HttpStringContent(CoolapkMessageException.RequestCaptcha))
             using (var code = new HttpStringContent(textbox.Text))
             {
                 content.Add(type, "type");
                 content.Add(code, "code");
                 UIHelper.ShowMessage((await DataHelper.PostDataAsync(DataUriType.RequestValidate, content)).ToString());
             }
 }
Ejemplo n.º 11
0
        /// <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);
        }
        /// <summary>
        /// Checks in at a given venue
        /// </summary>
        /// <param name="v">The venue to check-in</param>
        private async Task <bool> CheckinAsync(Venue v)
        {
            bool checkedIn    = false;
            bool accessDenied = false;

            var form = new HttpMultipartFormDataContent();

            form.Add(new HttpStringContent(v.Id), "venueId");
            form.Add(new HttpStringContent(v.Latitude.ToString() + "," + v.Longitude.ToString()), "ll");
            form.Add(new HttpStringContent("Geofencing 4Sq Sample auto-checkin"), "shout");
            form.Add(new HttpStringContent(Constants.ApiVerifiedDate), "v");

            try
            {
                var response = await _httpClient.PostAsync(new Uri("https://api.foursquare.com/v2/checkins/add"), form);

                switch (response.StatusCode)
                {
                case HttpStatusCode.Ok:
                    checkedIn = true;
                    ShowToast(v.Name + " checked in");
                    Logger.Trace(TraceLevel.Debug, v.Name + " checked in");
                    _checkinsCache = null;     // clear cache
                    break;

                case HttpStatusCode.Unauthorized:     // token was revoked
                    Logger.Trace(TraceLevel.Error, "User disconnected this app from the Foursquare Settings page: " + response.StatusCode.ToString());
                    accessDenied = true;
                    break;

                default:
                    Logger.Trace(TraceLevel.Error, "Failed to checkin to Foursquare: " + response.StatusCode.ToString());
                    break;
                }
            }
            catch (UnauthorizedAccessException)
            {
                accessDenied = true;
            }

            if (accessDenied)
            {
                Logger.Trace(TraceLevel.Info, "Access denied, deleting state.");
                await DeleteStateAsync();
            }

            return(checkedIn);
        }
Ejemplo n.º 13
0
        public async Task <WeiboResult> ShareImageAsync(byte[] image, string text)
        {
            if (image == null)
            {
                throw new ArgumentNullException(nameof(image));
            }

            if (text == null)
            {
                throw new ArgumentNullException(nameof(text));
            }

            if (string.IsNullOrWhiteSpace(text))
            {
                throw new ArgumentException("Text could not be empty", nameof(text));
            }

            if (!UserInfo.CheckUseable())
            {
                string authorizeCode = await this.GetAuthorizeCodeAsync();

                await this.Authorize(authorizeCode);
            }

            Uri uri = new Uri("https://upload.api.weibo.com/2/statuses/upload.json");

            HttpBufferContent bufferContent = new HttpBufferContent(image.AsBuffer());

            HttpMultipartFormDataContent content = new HttpMultipartFormDataContent();

            content.Add(new HttpStringContent(UserInfo.Token), "access_token");
            content.Add(new HttpStringContent(text), "status");
            content.Add(bufferContent, "pic", "pic.jpg");

            using (HttpClient client = new HttpClient())
            {
                HttpResponseMessage response;
                try
                {
                    response = await client.PostAsync(uri, content);
                }
                catch (Exception ex)
                {
                    throw new Exception("Network error", ex);
                }
                return(await response.Content.ReadAsJsonAsync <WeiboResult>());
            }
        }
Ejemplo n.º 14
0
        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());
            }
        }
Ejemplo n.º 15
0
        public async Task <IEnumerable <UploadResult> > UploadImagesAsync(IEnumerable <StorageFile> files, Action <HttpException> action = null)
        {
            var form = new HttpMultipartFormDataContent();

            foreach (var file in files)
            {
                form.Add(new HttpStreamContent(await file.OpenReadAsync()), "file[]", file.Name);
            }
            var data = await UploadAsync <string>("open/file/image", form, action);

            if (data == null)
            {
                return(null);
            }
            try
            {
                if (data.IndexOf("\"data\"") < 0)
                {
                    var res = JsonConvert.DeserializeObject <UploadResult>(data);
                    return(new UploadResult[] { res });
                }
                else
                {
                    var res = JsonConvert.DeserializeObject <ResponseData <UploadResult> > (data);
                    return(res.Data);
                }
            }
            catch (Exception)
            {
                return(null);
            }
        }
Ejemplo n.º 16
0
        public static async Task <string> PostResults(Uri url, Stream PostContent)
        {
            try
            {
                using (HttpClient hc = new HttpClient())
                {
                    //hc.DefaultRequestHeaders.Add("Content-Disposition", @"form-data; name=""img_file""");
                    //hc.DefaultRequestHeaders.Add("Content-Type", " application/octet-stream");
                    //hc.DefaultRequestHeaders.Add("Content-Type", "multipart/form-data;");
                    //hc.DefaultRequestHeaders.Add("Content-Length", PostContent.Length.ToString());
                    //hc.DefaultRequestHeaders.Host = new Windows.Networking.HostName(Home);
                    HttpMultipartFormDataContent httpMultipartFormDataContent = new HttpMultipartFormDataContent();
                    httpMultipartFormDataContent.Add(new HttpStreamContent(PostContent.AsInputStream()), "data");

                    //HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
                    //request.Content = httpMultipartFormDataContent;

                    HttpResponseMessage response = await hc.PostAsync(url, httpMultipartFormDataContent);

                    response.EnsureSuccessStatusCode();
                    string result = await response.Content.ReadAsStringAsync();

                    return(result);
                }
            }
            catch (Exception)
            {
                return("");
            }
        }
Ejemplo n.º 17
0
        private async void Start_Click(object sender, RoutedEventArgs e)
        {
            Helpers.ScenarioStarted(StartButton, CancelButton, OutputField);
            rootPage.NotifyUser("In progress", NotifyType.StatusMessage);

            try
            {
                HttpMultipartFormDataContent form = new HttpMultipartFormDataContent();
                form.Add(new HttpStringContent(RequestBodyField.Text), "data");

                // '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);

                HttpResponseMessage response = await httpClient.PostAsync(resourceAddress, form).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);
            }
        }
Ejemplo n.º 18
0
        /// <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);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Send file to create asset (image or video)
        /// </summary>
        /// <param name="itemToSend">Byte array of the file</param>
        /// <param name="fileName">File's name</param>
        /// <param name="contentType">File's content type </param>
        /// <returns></returns>
        public async Task <string> PostFileAssetAsync(byte[] itemToSend, string fileName, string contentType)
        {
            string resultJson = string.Empty;
            string parameters = $"/api/{this.ApiVersion}file_asset";

            try
            {
                HttpClient        request     = new HttpClient();
                var               content     = new HttpMultipartFormDataContent();
                HttpBufferContent itemContent = new HttpBufferContent(itemToSend.AsBuffer());
                itemContent.Headers.ContentType = HttpMediaTypeHeaderValue.Parse(contentType);
                content.Add(itemContent, "file_upload", fileName);
                using (HttpResponseMessage response = await request.PostAsync(new Uri(this.HttpLink + parameters), content))
                {
                    resultJson = await response.Content.ReadAsStringAsync();
                }

                if (!resultJson.Equals(string.Empty))
                {
                    return(JsonConvert.DeserializeObject <string>(resultJson));
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"[Device = {this.Name}; IP = {this.IpAddress}] Error while sending file.", ex);
            }
            return(null);
        }
Ejemplo n.º 20
0
        /// <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("");
            }
        }
Ejemplo n.º 21
0
        public async Task <TReturn> PostFormMultipartAsync <TReturn>(string address, Dictionary <string, string> formData, string boundary = "")
        {
            //  create a boundary if necessary
            if (string.IsNullOrEmpty(boundary))
            {
                boundary = Guid.NewGuid().ToString();
            }
            //  create content
            var content = new HttpMultipartFormDataContent(boundary);

            if ((formData != null) && (formData.Keys.Count > 0))
            {
                foreach (var key  in formData.Keys)
                {
                    content.Add(new HttpStringContent(formData[key], Windows.Storage.Streams.UnicodeEncoding.Utf8), key);
                }
            }
            //  make the call
            using (var client = new HttpClient())
            {
                await AddToken(client);

                var response = await client.PostAsync(new Uri(string.Format("{0}/{1}", _NetworkManager.BaseUrl, address)), content);

                return(await GetResponse <TReturn>(response));
            }
        }
Ejemplo n.º 22
0
        /// <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));
        }
Ejemplo n.º 23
0
        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));
        }
Ejemplo n.º 24
0
        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);
            }
        }
Ejemplo n.º 25
0
        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());
            }

        }
Ejemplo n.º 26
0
        public async Task <AIResponse> VoiceRequestAsync(Stream voiceStream, RequestExtras requestExtras = null)
        {
            var request = new AIRequest
            {
                Language  = config.Language.code,
                Timezone  = TimeZoneInfo.Local.StandardName,
                SessionId = sessionId
            };

            if (requestExtras != null)
            {
                if (requestExtras.HasContexts)
                {
                    request.Contexts = requestExtras.Contexts;
                }

                if (requestExtras.HasEntities)
                {
                    request.Entities = requestExtras.Entities;
                }
            }

            try
            {
                var content = new HttpMultipartFormDataContent();

                var jsonRequest = JsonConvert.SerializeObject(request, Formatting.None, jsonSettings);

                if (config.DebugLog)
                {
                    Debug.WriteLine($"Request: {jsonRequest}");
                }

                content.Add(new HttpStringContent(jsonRequest, UnicodeEncoding.Utf8, "application/json"), "request");
                content.Add(new HttpStreamContent(voiceStream.AsInputStream()), "voiceData", "voice.wav");

                var response = await httpClient.PostAsync(new Uri(config.RequestUrl), content);

                return(await ProcessResponse(response));
            }
            catch (Exception e)
            {
                throw new AIServiceException(e);
            }
        }
Ejemplo n.º 27
0
        private async Task <bool> CheckinAsync(Venue v)
        {
            bool checkedIn = false;

            try
            {
                var token = ApplicationData.Current.LocalSettings.Values[Constants.OAuthTokenKey];
                if (null != token)
                {
                    var form = new HttpMultipartFormDataContent();
                    form.Add(new HttpStringContent(v.Id), "venueId");
                    form.Add(new HttpStringContent(v.Latitude.ToString() + "," + v.Longitude.ToString()), "ll");
                    form.Add(new HttpStringContent("Geofencing4Sq sample auto-checkin"), "shout");
                    form.Add(new HttpStringContent((string)token), "oauth_token");
                    form.Add(new HttpStringContent(Constants.ApiVerifiedDate), "v");

                    _cts = new CancellationTokenSource();
                    HttpResponseMessage response = await _httpClient.PostAsync(new Uri("https://api.foursquare.com/v2/checkins/add"), form).AsTask(_cts.Token);

                    switch (response.StatusCode)
                    {
                    case HttpStatusCode.Ok:
                        checkedIn = true;
                        ShowToast(v.Name + " checked in");
                        break;

                    case HttpStatusCode.Unauthorized:
                        ApplicationData.Current.LocalSettings.Values[Constants.OAuthTokenKey] = null;
                        break;

                    default:
                        Logger.Trace(TraceLevel.Warn, "Failed to checkin to Foursquare: " + response.StatusCode.ToString());
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Trace(TraceLevel.Error, "Unable to checkin: " + Logger.FormatException(ex));
            }

            return(checkedIn);
        }
Ejemplo n.º 28
0
        internal static IAsyncOperationWithProgress <FileSearchResult, HttpProgress> SearchAsync(string keyword, Category category, StorageFile file, bool searchSimilar, bool onlyCovers, bool searchExpunged)
        {
            if (file is null)
            {
                throw new ArgumentNullException(nameof(file));
            }

            if (searchSimilar)
            {
                return(AsyncInfo.Run <FileSearchResult, HttpProgress>(async(token, progress) =>
                {
                    var read = FileIO.ReadBufferAsync(file);
                    HttpStringContent contentOf(bool v) => new HttpStringContent(v ? "1" : "0");
                    var data = new HttpMultipartFormDataContent
                    {
                        { contentOf(true), "fs_similar" },
                        { contentOf(onlyCovers), "fs_covers" },
                        { contentOf(searchExpunged), "fs_exp" }
                    };
                    var buf = await read;
                    data.Add(new HttpBufferContent(buf), "sfile", file.Name);
                    await data.BufferAllAsync();
                    var post = Client.Current.HttpClient.PostAsync(Client.Current.Uris.FileSearchUri, data);
                    post.Progress = (s, p) => progress.Report(p);
                    var r = await post;
                    var uri = r.RequestMessage.RequestUri;
                    var query = uri.Query.Split("?&".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                    var hashstr = query.Single(s => s.StartsWith("f_shash=")).Substring(8).Split(';');
                    var info = hashstr.FirstOrDefault(value => value.Length != 40);
                    switch (info)
                    {
                    case "monotone":
                        throw new InvalidOperationException(LocalizedStrings.Resources.UnsupportedMonotone);

                    case "corrupt":
                        throw new InvalidOperationException(LocalizedStrings.Resources.UnsupportedFile);

                    case null:
                        break;

                    default:
                        throw new InvalidOperationException(info);
                    }
                    return new FileSearchResult(keyword, category, hashstr.Select(SHA1Value.Parse), file.Name, true, onlyCovers, searchExpunged);
                }));
            }
            else
            {
                return(AsyncInfo.Run <FileSearchResult, HttpProgress>(async(token, progress) =>
                {
                    var hash = await SHA1Value.ComputeAsync(file);
                    return new FileSearchResult(keyword, category, Enumerable.Repeat(hash, 1), file.Name, false, onlyCovers, searchExpunged);
                }));
            }
        }
Ejemplo n.º 29
0
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            InputBox.Document.GetText(TextGetOptions.UseObjectText, out string contentText);
            contentText = contentText.Replace("\r", "\r\n");
            if (string.IsNullOrWhiteSpace(contentText))
            {
                return;
            }
            using (var content = new HttpMultipartFormDataContent(GetBoundary()))
            {
                switch (MakeFeedMode)
                {
                case MakeFeedMode.Feed:
                    using (var a = new HttpStringContent(contentText))
                        using (var b = new HttpStringContent("feed"))
                            using (var c = new HttpStringContent("0"))
                            {
                                content.Add(a, "message");
                                content.Add(b, "type");
                                content.Add(c, "is_html_article");
                                if (await DataHelper.PostDataAsync(DataUriType.CreateFeed, content) != null)
                                {
                                    SendSuccessful();
                                }
                            }
                    break;

                case MakeFeedMode.Reply:
                case MakeFeedMode.ReplyReply:
                    var type = MakeFeedMode == MakeFeedMode.Reply ? DataUriType.CreateFeedReply : DataUriType.CreateReplyReply;
                    using (var d = new HttpStringContent(contentText))
                    {
                        content.Add(d, "message");
                        if (await DataHelper.PostDataAsync(type, content, FeedId) != null)
                        {
                            SendSuccessful();
                        }
                    }
                    break;
                }
            }
        }
Ejemplo n.º 30
0
        public async ValueTask <HttpResponseMessage> PostMultiPartAsync(string path, IDictionary <string, IHttpContent> contents)
        {
            await EnsureTokenSavedAsync();

            var uri = new Uri(baseUri, path);

            using var multipartData = new HttpMultipartFormDataContent();
            foreach (var i in contents)
            {
                if (string.IsNullOrEmpty(i.Key))
                {
                    multipartData.Add(i.Value);
                }
                else
                {
                    multipartData.Add(i.Value, i.Key);
                }
            }
            return(await httpClient.PostAsync(uri, multipartData));
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Запостить на стену
        /// </summary>
        /// <param name="groupId">Id группы</param>
        /// <param name="fromGroup">Добавить запись от лица группы</param>
        /// <param name="message">Текст</param>
        /// <param name="attachments">Прикрепленные документы</param>
        /// <returns></returns>
        public async Task <bool> Post(string groupId, bool fromGroup, string message, List <Attachment> attachments, DateTimeOffset?publishDate = null)
        {
            string attachmentsString = "";
            // Получаем сервер для загрузки фото
            var uploadServer = await GetWallUploadServer(groupId);

            var client = new HttpClient();

            foreach (var attach in attachments)
            {
                string fileName = $"PostImages\\{attach.Photo.Id}.png";

                // Скачиваем фото из группы
                var file = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

                BackgroundDownloader downloader = new BackgroundDownloader();
                DownloadOperation    download   = downloader.CreateDownload(new Uri(attach.Photo.BiggestPhoto), file);
                await download.StartAsync();

                //Загружаем фото на сервер
                var multipart = new HttpMultipartFormDataContent();
                multipart.Add(new HttpStreamContent(await file.OpenAsync(FileAccessMode.Read)), "file", fileName);
                var response = await client.PostAsync(new Uri(uploadServer.Upload_Url), multipart);

                var uploadResult = Newtonsoft.Json.JsonConvert.DeserializeObject <UploadResult>(await response.Content.ReadAsStringAsync());

                // Удаляем локальный файл
                await file.DeleteAsync();

                // Сохраняем фото на стене
                var photo = await SaveWallPhoto(groupId, uploadResult);

                attachmentsString += $"photo{photo.Owner_Id}_{photo.Id},";
            }

            // Формируем запрос
            var request = new RestRequest("wall.post", Method.POST);

            request.AddParameter("owner_id", $"-{groupId}");
            request.AddParameter("from_group", fromGroup);
            request.AddParameter("message", message);
            request.AddParameter("attachments", attachmentsString);

            if (publishDate != null)
            {
                var unixTimestamp = (publishDate.Value.UtcDateTime.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
                request.AddParameter("publish_date", unixTimestamp);
            }

            var result = await Execute <object>(request);

            return(result != null);
        }
        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
            {
                HttpMultipartFormDataContent form = new HttpMultipartFormDataContent();
                form.Add(new HttpStringContent(RequestBodyField.Text), "data");

                HttpResponseMessage response = await httpClient.PostAsync(resourceAddress, form).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);
            }
        }
Ejemplo n.º 33
0
 public static async Task<string> HttpPostStreamAsync(string url, StorageFile reqFile, CancellationToken token = new CancellationToken())
 {
     using (var httpFilter = new HUwpHttpFilter())
     using (var client = new HttpClient(httpFilter))
     {
         var form = new HttpMultipartFormDataContent();
         var inStream = await reqFile.OpenAsync(FileAccessMode.Read);
         form.Add(new HttpStreamContent(inStream), "file", reqFile.Name);
         var response = await client.PostAsync(new Uri(url), form);
         response.EnsureSuccessStatusCode();
         var resStr = await response.Content.ReadAsStringAsync();
         return resStr;
     }
 }
Ejemplo n.º 34
0
        public async Task<AIResponse> VoiceRequestAsync(Stream voiceStream, RequestExtras requestExtras = null)
        {
            var request = new AIRequest
            {
                Language = config.Language.code,
                Timezone = TimeZoneInfo.Local.StandardName,
                SessionId = sessionId
            };

            if (requestExtras != null)
            {
                if (requestExtras.HasContexts)
                {
                    request.Contexts = requestExtras.Contexts;
                }

                if (requestExtras.HasEntities)
                {
                    request.Entities = requestExtras.Entities;
                }
            }

            try
            {
                var content = new HttpMultipartFormDataContent();
                
                var jsonRequest = JsonConvert.SerializeObject(request, Formatting.None, jsonSettings);

                if (config.DebugLog)
                {
                    Debug.WriteLine($"Request: {jsonRequest}");
                }

                content.Add(new HttpStringContent(jsonRequest, UnicodeEncoding.Utf8, "application/json"), "request");
                content.Add(new HttpStreamContent(voiceStream.AsInputStream()), "voiceData", "voice.wav");
                
                var response = await httpClient.PostAsync(new Uri(config.RequestUrl), content);
                return await ProcessResponse(response);
            }
            catch (Exception e)
            {
                throw new AIServiceException(e);
            }
        }
Ejemplo n.º 35
0
        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);

        }
Ejemplo n.º 36
0
        Task<AsyncResponse> HttpPostWithMultipartFormDataAsync(string url, IEnumerable<KeyValuePair<string, object>> prm, string authorizationHeader, ConnectionOptions options, CancellationToken cancellationToken)
        {
            if(options == null) options = new ConnectionOptions();

#if WIN_RT
            var client = new HttpClient();
            var req = new HttpRequestMessage(HttpMethod.Post, new Uri(url));
#if WIN8
            var content = new MultipartFormDataContent();
#else
            var content = new HttpMultipartFormDataContent();
#endif
            foreach(var x in prm)
            {
                cancellationToken.ThrowIfCancellationRequested();

                var valueStream = x.Value as Stream;
                var valueInputStream = x.Value as IInputStream;
                var valueBytes = x.Value as IEnumerable<byte>;
                var valueBuffer = x.Value as IBuffer;
                var valueInputStreamReference = x.Value as IInputStreamReference;
                var valueStorageItem = x.Value as IStorageItem;

                if(valueInputStreamReference != null)
                    valueInputStream = await valueInputStreamReference.OpenSequentialReadAsync();

#if WIN8
                if(valueInputStream != null)
                    valueStream = valueInputStream.AsStreamForRead();
                if(valueBuffer != null)
                    valueStream = valueBuffer.AsStream();

                if(valueStream != null)
                    content.Add(new StreamContent(valueStream), x.Key, valueStorageItem != null ? valueStorageItem.Name : "file");
                else if(valueBytes != null)
                {
                    var valueByteArray = valueBytes as byte[];
                    if(valueByteArray == null) valueByteArray = valueBytes.ToArray();
                    content.Add(new ByteArrayContent(valueByteArray), x.Key, valueStorageItem != null ? valueStorageItem.Name : "file");
                }
                else
                    content.Add(new StringContent(x.Value.ToString()), x.Key);
#else
                if (valueStream != null)
                    valueInputStream = valueStream.AsInputStream();
                if (valueBytes != null)
                {
                    var valueByteArray = valueBytes as byte[];
                    if (valueByteArray == null) valueByteArray = valueBytes.ToArray();
                    valueBuffer = valueByteArray.AsBuffer();
                }

                if (valueInputStream != null)
                    content.Add(new HttpStreamContent(valueInputStream), x.Key, valueStorageItem != null ? valueStorageItem.Name : "file");
                else if (valueBuffer != null)
                    content.Add(new HttpBufferContent(valueBuffer), x.Key, valueStorageItem != null ? valueStorageItem.Name : "file");
                else
                    content.Add(new HttpStringContent(x.Value.ToString()), x.Key);
#endif
            }
            cancellationToken.ThrowIfCancellationRequested();
            req.Content = content;
            return await ExecuteRequest(client, req, authorizationHeader, options, cancellationToken).ConfigureAwait(false);
#else
            return Task.Factory.StartNew(() =>
            {
                cancellationToken.ThrowIfCancellationRequested();
                var task = new TaskCompletionSource<AsyncResponse>();

                var boundary = Guid.NewGuid().ToString();
                var req = (HttpWebRequest)WebRequest.Create(url);

                var reg = cancellationToken.Register(() =>
                {
                    task.TrySetCanceled();
                    req.Abort();
                });

#if NET45 || WP
                req.AllowReadStreamBuffering = false;
#endif
                req.Method = "POST";
#if !(PCL || WP)
                req.ServicePoint.Expect100Continue = false;
                req.ReadWriteTimeout = options.ReadWriteTimeout;
#endif
#if !PCL
                req.UserAgent = options.UserAgent;
#endif
#if !(PCL || WP)
                req.Proxy = options.Proxy;
#endif
                req.ContentType = "multipart/form-data;boundary=" + boundary;
                req.Headers[HttpRequestHeader.Authorization] = authorizationHeader;
                cancellationToken.ThrowIfCancellationRequested();
                var memstr = new MemoryStream();
                try
                {
                    WriteMultipartFormData(memstr, boundary, prm);
                    cancellationToken.ThrowIfCancellationRequested();
#if !PCL
                    req.ContentLength = memstr.Length;
                    if(options.BeforeRequestAction != null) options.BeforeRequestAction(req);
#endif

                    var timeoutCancellation = new CancellationTokenSource();
                    DelayAction(options.Timeout, timeoutCancellation.Token, () =>
                    {
#if PCL
                        task.TrySetException(new TimeoutException());
#else
                        task.TrySetException(new WebException("Timeout", WebExceptionStatus.Timeout));
#endif
                        req.Abort();
                    });
                    req.BeginGetRequestStream(reqStrAr =>
                    {
                        try
                        {
                            using(var stream = req.EndGetRequestStream(reqStrAr))
                                memstr.WriteTo(stream);

                            req.BeginGetResponse(resAr =>
                            {
                                timeoutCancellation.Cancel();
                                reg.Dispose();
                                try
                                {
                                    task.TrySetResult(new AsyncResponse((HttpWebResponse)req.EndGetResponse(resAr)));
                                }
                                catch(Exception ex)
                                {
                                    task.TrySetException(ex);
                                }
                            }, null);
                        }
                        catch(Exception ex)
                        {
                            task.TrySetException(ex);
                        }
                        finally
                        {
                            memstr.Dispose();
                        }
                    }, null);

                    return task.Task;
                }
                catch
                {
                    memstr.Dispose();
                    throw;
                }
            }, cancellationToken).CheckCanceled(cancellationToken).Unwrap();
#endif
        }
Ejemplo n.º 37
0
 public async Task SendData()
 {
     var client = new HttpClient();
     var content = new HttpMultipartFormDataContent();
     var imageContent = new HttpBufferContent(data.imageBuffer);
     content.Add(imageContent, "userpic", "userpic.bmp");
     var name = new HttpStringContent(data.name);
     content.Add(name, "name");
     var color = new HttpStringContent(data.color.color.ToString());
     content.Add(color, "color");
     var stick = new HttpStringContent(data.stickNum);
     content.Add(stick, "stick");
     var gid = new HttpStringContent(data.gameId);
     content.Add(gid, "gid");
     try
     {
         var res = await client.PostAsync(new Uri("http://mspjp-iot-test.azurewebsites.net/insertUser"), content);
         if (!res.IsSuccessStatusCode)
         {
             throw new Exception("Access failed." + res.ReasonPhrase);
         }
     }
     catch (Exception ex)
     {
         var message = new MessageDialog(ex.Message, "ふむ。最初からやり直しですな。");
         await message.ShowAsync();
         this.Frame.Navigate(typeof(InitPage01));
     }
 }
Ejemplo n.º 38
0
        private async Task SendStick(Stick stick)
        {
            var client = new HttpClient();
            var content = new HttpMultipartFormDataContent();

            var stickNum = new HttpStringContent(stick.num);
            var raspiNum = new HttpStringContent(RasPiData.number.ToString());

            content.Add(stickNum, "stick");
            content.Add(raspiNum, "rpi");
            HttpResponseMessage res;
            try
            {
                res = await client.PostAsync(new Uri("http://mspjp-iot-test.azurewebsites.net/fromRpi"), content);

            }
            catch (Exception ex)
            {
                debugBox.Text = ex.Message;
            }
        }
Ejemplo n.º 39
0
        /// <summary>
        /// Send password to decrypt the crypted library
        /// </summary>
        public async void decryptLibrary()
        {
            var filter = new HttpBaseProtocolFilter();
            string t = uristringRequestLibrary + GlobalVariables.currentLibrary + "/";

            Uri a = new Uri(t);

            // *******************
            // IGNORING CERTIFACTE PROBLEMS
            // *******************
            filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.IncompleteChain);
            filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Expired);
            filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
            filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName);

            var HttpClientDecryptLibrary = new HttpClient(filter);
            HttpMultipartFormDataContent requestDecryptLibrary = new HttpMultipartFormDataContent();

            HttpClientDecryptLibrary.DefaultRequestHeaders.Add("Accept", "application/json;indent=4");
            HttpClientDecryptLibrary.DefaultRequestHeaders.Add("Authorization", "token " + authorizationToken);


            var values = new List<KeyValuePair<string, string>>
                    {
                        new KeyValuePair<string, string>("password", GlobalVariables.currentLibraryPassword)
                    };

            foreach (var keyValuePair in values)
            {
                requestDecryptLibrary.Add(new HttpStringContent(keyValuePair.Value), keyValuePair.Key);
            }

            try
            {
                HttpResponseMessage responseDecryptLibrary = await HttpClientDecryptLibrary.PostAsync(a, requestDecryptLibrary);
                responseDecryptLibrary.EnsureSuccessStatusCode();

                if (GlobalVariables.IsDebugMode == true)
                {
                    App.logger.log(LogLevel.debug, "Decrypt library OK");
                }
                NavigationService.Navigate(new Uri("/Pages/ContentLibraryPage.xaml?token=" + authorizationToken + "&url=" + address + "&idlibrary=" + GlobalVariables.currentLibrary, UriKind.Relative));
         
            }
            catch (Exception ex)
            {
                if (GlobalVariables.IsDebugMode == true)
                {
                    App.logger.log(LogLevel.critical, "The library password is wrong");
                    App.logger.log(LogLevel.critical, "Exception : " + ex);
                }
                MessageBox.Show(AppResources.ListLibrary_LibCrypt_Error_Content, AppResources.ListLibrary_LibCrypt_Error_Title, MessageBoxButton.OK);
            }
        }
Ejemplo n.º 40
0
        //发送录音
        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;
             }
        }
Ejemplo n.º 41
0
        /// <summary>
        /// Sends a POST request with multipart/form-data as an asynchronous operation.
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <param name="prm">The parameters.</param>
        /// <param name="authorizationHeader">The OAuth header.</param>
        /// <param name="options">The connection options for the request.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// <para>The task object representing the asynchronous operation.</para>
        /// <para>The Result property on the task object returns the response.</para>
        /// </returns>
        internal static async Task<AsyncResponse> HttpPostWithMultipartFormDataAsync(Uri url, KeyValuePair<string, object>[] prm, string authorizationHeader, ConnectionOptions options, CancellationToken cancellationToken, IProgress<UploadProgressInfo> progress)
        {
            if(options == null) options = ConnectionOptions.Default;

            var req = new HttpRequestMessage(HttpMethod.Post, url);
            var toDispose = new List<IDisposable>();

#if WIN_RT
            var content = new HttpMultipartFormDataContent();
            foreach(var x in prm)
            {
                cancellationToken.ThrowIfCancellationRequested();

                var valueStream = x.Value as Stream;
                var valueInputStream = x.Value as IInputStream;
                var valueArraySegment = x.Value as ArraySegment<byte>?;
                var valueBytes = x.Value as IEnumerable<byte>;
                var valueBuffer = x.Value as IBuffer;
                var valueInputStreamReference = x.Value as IInputStreamReference;
                var valueStorageItem = x.Value as IStorageItem;

                var fileName = "file";

                if (valueStorageItem != null)
                {
                    fileName = valueStorageItem.Name;
                }
                else if (x.Value.GetType().FullName == "System.IO.FileInfo")
                {
                    var ti = x.Value.GetType().GetTypeInfo();
                    valueStream = (Stream)ti.GetDeclaredMethod("OpenRead").Invoke(x.Value, null);
                    fileName = (string)ti.GetDeclaredProperty("Name").GetValue(x.Value);
                    toDispose.Add(valueStream);
                }

                if (valueInputStreamReference != null)
                {
                    valueInputStream = await valueInputStreamReference.OpenSequentialReadAsync().AsTask().ConfigureAwait(false);
                    toDispose.Add(valueInputStream);
                }
                else if (valueStream != null)
                {
                    valueInputStream = valueStream.AsInputStream();
                }
                else if (valueArraySegment != null)
                {
                    valueBuffer = valueArraySegment.Value.Array.AsBuffer(valueArraySegment.Value.Offset, valueArraySegment.Value.Count);
                }
                else if (valueBytes != null)
                {
                    var valueByteArray = valueBytes as byte[] ?? valueBytes.ToArray();
                    valueBuffer = valueByteArray.AsBuffer();
                }

                if(valueInputStream != null)
                    content.Add(new HttpStreamContent(valueInputStream), x.Key, fileName);
                else if(valueBuffer != null)
                    content.Add(new HttpBufferContent(valueBuffer), x.Key, fileName);
                else
                    content.Add(new HttpStringContent(x.Value.ToString()), x.Key);
            }
#else
            var content = new MultipartFormDataContent();
            foreach (var x in prm)
            {
                cancellationToken.ThrowIfCancellationRequested();

                var valueStream = x.Value as Stream;
                if (valueStream != null)
                {
                    content.Add(new StreamContent(valueStream), x.Key, "file");
                    continue;
                }

                var valueArraySegment = x.Value as ArraySegment<byte>?;
                if (valueArraySegment != null)
                {
                    content.Add(
                        new ByteArrayContent(valueArraySegment.Value.Array, valueArraySegment.Value.Offset, valueArraySegment.Value.Count),
                        x.Key, "file");
                    continue;
                }

                var valueBytes = x.Value as IEnumerable<byte>;
                if (valueBytes != null)
                {
                    content.Add(new ByteArrayContent(valueBytes as byte[] ?? valueBytes.ToArray()), x.Key, "file");
                    continue;
                }

#if FILEINFO
                var valueFileInfo = x.Value as FileInfo;
                if (valueFileInfo != null)
                {
                    valueStream = valueFileInfo.OpenRead();
                    content.Add(new StreamContent(valueStream), x.Key, valueFileInfo.Name);
                    toDispose.Add(valueStream);
                    continue;
                }
#else
                var fileInfoType = x.Value.GetType();
                if (fileInfoType.FullName == "System.IO.FileInfo")
                {
                    var ti = fileInfoType.GetTypeInfo();
                    valueStream = (Stream)ti.GetDeclaredMethod("OpenRead").Invoke(x.Value, null);
                    content.Add(new StreamContent(valueStream), x.Key, (string)ti.GetDeclaredProperty("Name").GetValue(x.Value));
                    toDispose.Add(valueStream);
                    continue;
                }
#endif

                content.Add(new StringContent(x.Value.ToString()), x.Key);
            }
#endif

            cancellationToken.ThrowIfCancellationRequested();
            req.Content = content;
            var res = await ExecuteRequest(req, authorizationHeader, options, cancellationToken, progress).ConfigureAwait(false);

            foreach (var x in toDispose)
                x.Dispose();

            return res;
        }
Ejemplo n.º 42
0
 public async void ImportPicture()
 {
     var picturePicker = new PicturePicker();
     var pictures = await picturePicker.openPicker.PickMultipleFilesAsync();
     if (pictures.Count > 0)
     {
         var i = 0;
         IsLoading(true, "importing");
         foreach (var picture in pictures)
         {
             SetLoadingText("Importing pictures... (" + i + "/" + pictures.Count() + ")");
             using (IInputStream stream = await picture.OpenAsync(FileAccessMode.Read))
             {
                 var multipartContent = new HttpMultipartFormDataContent();
                 multipartContent.Add(new HttpStreamContent(stream), "newPicture", picture.Name);
                 var uri = new Uri("http://" + serverIP + "/server/requestHandler.php?operation=import");
                 var client = new HttpClient();
                 var response = await client.PostAsync(uri, multipartContent);
                 if (!response.Content.ToString().Contains("Success"))
                 {
                     MessageDialog dialog = new MessageDialog(response.Content.ToString());
                     await dialog.ShowAsync();
                 }
             }
             i++;
         }
         IsLoading(true, "pictures");
         await SharedFunctions.GetPicturesAndUpdateGridView();
         IsLoading(false, "pictures");
     }
 }
Ejemplo n.º 43
0
        Task<AsyncResponse> HttpPostWithMultipartFormDataAsync(Uri url, IEnumerable<KeyValuePair<string, object>> prm, string authorizationHeader, ConnectionOptions options, CancellationToken cancellationToken)
        {
            if(options == null) options = new ConnectionOptions();

#if WIN_RT || PCL
            var req = new HttpRequestMessage(HttpMethod.Post, url);
#endif
#if WIN_RT
            var content = new HttpMultipartFormDataContent();
            foreach(var x in prm)
            {
                cancellationToken.ThrowIfCancellationRequested();

                var valueStream = x.Value as Stream;
                var valueInputStream = x.Value as IInputStream;
                var valueBytes = x.Value as IEnumerable<byte>;
                var valueBuffer = x.Value as IBuffer;
                var valueInputStreamReference = x.Value as IInputStreamReference;
                var valueStorageItem = x.Value as IStorageItem;

                if(valueInputStreamReference != null)
                    valueInputStream = await valueInputStreamReference.OpenSequentialReadAsync();

                if(valueStream != null)
                    valueInputStream = valueStream.AsInputStream();
                if(valueBytes != null)
                {
                    var valueByteArray = valueBytes as byte[] ?? valueBytes.ToArray();
                    valueBuffer = valueByteArray.AsBuffer();
                }

                if(valueInputStream != null)
                    content.Add(new HttpStreamContent(valueInputStream), x.Key, valueStorageItem?.Name ?? "file");
                else if(valueBuffer != null)
                    content.Add(new HttpBufferContent(valueBuffer), x.Key, valueStorageItem?.Name ?? "file");
                else
                    content.Add(new HttpStringContent(x.Value.ToString()), x.Key);
            }
            cancellationToken.ThrowIfCancellationRequested();
            req.Content = content;
            return await ExecuteRequest(req, authorizationHeader, options, cancellationToken).ConfigureAwait(false);
#elif PCL
            var content = new MultipartFormDataContent();
            foreach (var x in prm)
            {
                var valueStream = x.Value as Stream;
                var valueBytes = x.Value as IEnumerable<byte>;

                if(valueStream != null)
                    content.Add(new StreamContent(valueStream), x.Key, "file");
                else if(valueBytes != null)
                    content.Add(new ByteArrayContent(valueBytes as byte[] ?? valueBytes.ToArray()), x.Key, "file");
                else
                    content.Add(new StringContent(x.Value.ToString()), x.Key);
            }
            req.Content = content;
            return ExecuteRequest(req, authorizationHeader, options, cancellationToken);
#else
            var task = new TaskCompletionSource<AsyncResponse>();
            if(cancellationToken.IsCancellationRequested)
            {
                task.TrySetCanceled();
                return task.Task;
            }

            try
            {
                var boundary = Guid.NewGuid().ToString();
                var req = (HttpWebRequest)WebRequest.Create(url);

                var reg = cancellationToken.Register(() =>
                {
                    task.TrySetCanceled();
                    req.Abort();
                });

                req.Method = "POST";
#if !WP
                req.ServicePoint.Expect100Continue = false;
                req.ReadWriteTimeout = options.ReadWriteTimeout;
                req.Proxy = options.Proxy;
                req.SendChunked = true;
                if(options.UseCompression)
                    req.AutomaticDecompression = CompressionType;
                if (options.DisableKeepAlive)
                    req.KeepAlive = false;
#endif
                req.UserAgent = options.UserAgent;
                req.ContentType = "multipart/form-data;boundary=" + boundary;
                req.Headers[HttpRequestHeader.Authorization] = authorizationHeader;
                options.BeforeRequestAction?.Invoke(req);

                var timeoutCancellation = new CancellationTokenSource();
                DelayAction(options.Timeout, timeoutCancellation.Token, () =>
                {
                    task.TrySetCanceled();
                    req.Abort();
                });
                req.BeginGetRequestStream(reqStrAr =>
                {
                    try
                    {
                        using(var stream = req.EndGetRequestStream(reqStrAr))
                            WriteMultipartFormData(stream, boundary, prm);

                        req.BeginGetResponse(resAr =>
                        {
                            timeoutCancellation.Cancel();
                            reg.Dispose();
                            try
                            {
                                task.TrySetResult(new AsyncResponse((HttpWebResponse)req.EndGetResponse(resAr)));
                            }
                            catch(Exception ex)
                            {
                                task.TrySetException(ex);
                            }
                        }, null);
                    }
                    catch(Exception ex)
                    {
                        task.TrySetException(ex);
                    }
                }, null);
            }
            catch(Exception ex)
            {
                task.TrySetException(ex);
            }

            return task.Task;
#endif
        }
Ejemplo n.º 44
0
        private async void UploadFile(string url, StorageFile file)
        {
            try
            {
                Stream data = await file.OpenStreamForReadAsync();

                if (data.Length > maxsize)
                    throw new Exception("Файл не должен превышать 200 МБ.");

                var client = new Windows.Web.Http.HttpClient();
                var content = new HttpMultipartFormDataContent();
                content.Add(new HttpStreamContent(data.AsInputStream()), "file", file.Name);
                var postAsyncOp = client.PostAsync(new Uri(url), content);

                postAsyncOp.Progress = async (r, progress) =>
                {
                    if (progress.TotalBytesToSend.HasValue && progress.TotalBytesToSend > 0)
                    {
                        await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                        () =>
                        {
                            statusText.Text = Math.Round((((double)progress.BytesSent * 100) / progress.TotalBytesToSend.Value), 0).ToString() + " %";

                        });
                    }
                };

                var result = await postAsyncOp;

                //fileToAdd = file;
                JSONAddedFileResponse = await result.Content.ReadAsStringAsync();

                nameDocumentAdd.Text = fileToAdd.Name;

                uploadGrid.Visibility = Visibility.Collapsed;
                AddDocumentGrid.Visibility = Visibility.Visible;
                CommandBar.Visibility = Visibility.Collapsed;
            }
            catch(Exception e)
            {

                uploadGrid.Visibility = Visibility.Collapsed;
                AddDocumentGrid.Visibility = Visibility.Collapsed;
                CommandBar.Visibility = Visibility.Visible;

                MessageDialog dialog = new MessageDialog("Не удалось начать загрузку документа. " + e.Message);
                dialog.Commands.Add(new UICommand("Ок", new UICommandInvokedHandler(CommandHandlers)));
                await dialog.ShowAsync();
            }


        }
        public static async void Upload(string uri, Stream data, string paramName, string uploadContentType,Action<VKHttpResult> resultCallback, Action<double> progressCallback = null, string fileName = null)
        {
#if SILVERLIGHT
            var rState = new RequestState();
            rState.resultCallback = resultCallback;
#endif
            try
            {
#if SILVERLIGHT
                var request = (HttpWebRequest)WebRequest.Create(uri);
            
                request.AllowWriteStreamBuffering = false;
                rState.request = request;
                request.Method = "POST";
                string formDataBoundary = String.Format("----------{0:N}", Guid.NewGuid());
                string contentType = "multipart/form-data; boundary=" + formDataBoundary;
                request.ContentType = contentType;
                request.CookieContainer = new CookieContainer();

                string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\";\r\nContent-Type: {3}\r\n\r\n",
                               formDataBoundary,
                               paramName,
                               fileName ?? "myDataFile",
                               uploadContentType);

                string footer = "\r\n--" + formDataBoundary + "--\r\n";

                request.ContentLength = Encoding.UTF8.GetByteCount(header) + data.Length + Encoding.UTF8.GetByteCount(footer);

                request.BeginGetRequestStream(ar =>
                {
                    try
                    {
                        var requestStream = request.EndGetRequestStream(ar);

                        requestStream.Write(Encoding.UTF8.GetBytes(header), 0, Encoding.UTF8.GetByteCount(header));

                        StreamUtils.CopyStream(data, requestStream, progressCallback);

                        requestStream.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer));

                        requestStream.Close();

                        request.BeginGetResponse(new AsyncCallback(ResponseCallback), rState);
                    }
                    catch (Exception ex)
                    {
                        Logger.Error("VKHttpRequestHelper.Upload failed to write data to request stream.", ex);
                        SafeClose(rState);
                        SafeInvokeCallback(rState.resultCallback, false, null);
                    }

                }, null);
#else

                var httpClient = new Windows.Web.Http.HttpClient();
                HttpMultipartFormDataContent content = new HttpMultipartFormDataContent();
                content.Add(new HttpStreamContent(data.AsInputStream()), paramName, fileName ?? "myDataFile");
                content.Headers.Add("Content-Type", uploadContentType);
                var postAsyncOp =  httpClient.PostAsync(new Uri(uri, UriKind.Absolute),
                    content);

                postAsyncOp.Progress = (r, progress) =>
                    {
                        if (progressCallback != null && progress.TotalBytesToSend.HasValue && progress.TotalBytesToSend > 0)
                        {
                            progressCallback(((double)progress.BytesSent * 100) / progress.TotalBytesToSend.Value);
                        }
                    };


                var result = await postAsyncOp;

                var resultStr = await result.Content.ReadAsStringAsync();

                SafeInvokeCallback(resultCallback, result.IsSuccessStatusCode, resultStr);
#endif
            }
            catch (Exception exc)
            {
                Logger.Error("VKHttpRequestHelper.Upload failed.", exc);
#if SILVERLIGHT
                SafeClose(rState);
                   SafeInvokeCallback(rState.resultCallback, false, null);
#else
                SafeInvokeCallback(resultCallback, false, null);
#endif

            }
        }
Ejemplo n.º 46
0
        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;
            }
        }
Ejemplo n.º 47
0
        public async Task<String> sendSnap(String username, String password, ProgressBar progressBar, String userTo, StorageFile file, int time)
        {
            HttpResponseMessage response = null;
            String responseString = null;

            _progressBar = progressBar;
            _progressBar.Visibility = Windows.UI.Xaml.Visibility.Visible;

            try
            {
                IInputStream inputStream = await file.OpenAsync(FileAccessMode.Read);

                String device_id = h.getDeviceID();
                HttpMultipartFormDataContent multipartContent = new HttpMultipartFormDataContent();

                Debug.WriteLine("sendSnap | File name: " + file.Name);

                multipartContent.Add(
                    new HttpStreamContent(inputStream),
                    "snap",
                    file.Name);

                multipartContent.Add(new HttpStringContent(username), "username");
                multipartContent.Add(new HttpStringContent(password), "password");
                multipartContent.Add(new HttpStringContent(h.getDeviceID()), "device_id");
                multipartContent.Add(new HttpStringContent(userTo), "send_snap_to");
                multipartContent.Add(new HttpStringContent(time.ToString()), "send_snap_time");

                IProgress<HttpProgress> progress = new Progress<HttpProgress>(ProgressHandler);
                response = await httpClient.PostAsync(new Uri(settings.API + "/send_snap/"), multipartContent).AsTask(cts.Token, progress);
                responseString = await response.Content.ReadAsStringAsync();
                Debug.WriteLine("sendSnap | responseString: " + responseString);
            }
            catch (TaskCanceledException)
            {
                Debug.WriteLine("sendSnap | Canceled");
            }
            catch (Exception ex)
            {
                Debug.WriteLine("sendSnap | Error: " + ex.StackTrace);
            }
            finally
            {
                Debug.WriteLine("sendSnap | Completed");
                resetProgressBar();
            }

            return responseString;
        }
        /// <summary>
        /// 分享图片到微博
        /// </summary>
        /// <param name="image">图片数据</param>
        /// <param name="text">图片描述</param>
        /// <returns>分享结果</returns>
        /// <exception cref="ArgumentNullException">image 为 null</exception>
        /// <exception cref="ArgumentNullException">text 为 null</exception>
        /// <exception cref="ArgumentException">text 为空字符串</exception>
        /// <exception cref="AuthorizeException">授权已过期,并且用户取消重新授权</exception>
        /// <exception cref="HttpException">网络异常</exception>
        /// <remarks>执行完成后请检查对象的 IsSuccess 属性,以获取是否成功</remarks>
        public async Task<Models.Weibo> ShareImageAsync(byte[] image, string text)
        {
            if (image == null)
            {
                throw new ArgumentNullException(nameof(image));
            }

            if (text == null)
            {
                throw new ArgumentNullException(nameof(text));
            }

            if (string.IsNullOrWhiteSpace(text))
            {
                throw new ArgumentException("text could not be empty", nameof(text));
            }

            if (LocalAccessToken.Useable == false)
            {
                string authorizeCode = await GetAuthorizeCodeAsync();
                await Authorize(authorizeCode);
            }

            Uri uri = new Uri("https://upload.api.weibo.com/2/statuses/upload.json");

            HttpBufferContent bufferContent = new HttpBufferContent(image.AsBuffer());

            HttpMultipartFormDataContent content = new HttpMultipartFormDataContent();

            content.Add(new HttpStringContent(LocalAccessToken.Token), "access_token");
            content.Add(new HttpStringContent(text), "status");
            content.Add(bufferContent, "pic", "pic.jpg");

            using (HttpClient client = new HttpClient())
            {
                HttpResponseMessage response;
                try
                {
                    response = await client.PostAsync(uri, content);
                }
                catch (Exception ex)
                {
                    throw new HttpException("network error", ex);
                }
                return await response.Content.ReadAsJsonAsync<Models.Weibo>();
            }
        }
Ejemplo n.º 49
0
        private async void uploadphoto_Click(object sender, RoutedEventArgs e)
        {
            HttpClient htpc = new HttpClient();
            HttpMultipartFormDataContent form = new HttpMultipartFormDataContent();

            string teamid = ApplicationData.Current.LocalSettings.Values["currentTeamID"].ToString();
            string memberid = (string)ApplicationData.Current.LocalSettings.Values["currentMemberIDforLoggedInUser"].ToString();
            form.Add(new HttpStringContent(teamid), "team_id");
            form.Add(new HttpStringContent(memberid), "member_id");
            form.Add(new HttpStringContent("image"), "media_format");
            form.Add(new HttpStringContent(team_media_group_id), "team_media_group_id");
            form.Add(new HttpStringContent("TestingImageUpload"), "description");
            form.Add(new HttpStringContent(team_media_group_id), "team_media_group_id");
            form.Add(new HttpStringContent(upload_position.ToString()), "position");
            BitmapImage bmp = new BitmapImage(new Uri("ms-appx:///assets/logo.png"));
            Windows.Storage.Streams.IRandomAccessStream random = await Windows.Storage.Streams.RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///assets/logo.png")).OpenReadAsync();
            Windows.Graphics.Imaging.BitmapDecoder decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(random);
            Windows.Graphics.Imaging.PixelDataProvider pixelData = await decoder.GetPixelDataAsync();
            byte[] bytes = pixelData.DetachPixelData();
            /************************************************************************************************************************/
            GetMultipartFormData();
            

            /************************************************************************************************************************/

            form.Add(new HttpStringContent(bytes.ToString()), "file");
            
            MemoryStream ms = new MemoryStream();

        }
Ejemplo n.º 50
0
        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());
              
            }

        }
Ejemplo n.º 51
0
        private async Task<HttpRequestMessage> BuildMultipartWebRequest(IORequest request, IOService service, string requestUriString)
        {

            var webRequest = new HttpRequestMessage(HttpMethod.Post, new Uri(requestUriString));
            webRequest.Headers.Add("Keep-Alive", "true");
            var sBoundary = "----------" + DateTime.Now.Ticks.ToString("x");
            var multipartFormDataContent = new HttpMultipartFormDataContent(sBoundary);

            if (request.Content != null)
            {
                var items = request.Content.TrimEnd('&').Split('&');
                foreach (var keyValue in items.Select(item => item.Split('=')))
                {
                    multipartFormDataContent.Add(new HttpStringContent(keyValue[1]), keyValue[0]);
                }
            }
            webRequest.Content = multipartFormDataContent;
            if (request.Attachment == null) return webRequest;
            foreach (var attachData in request.Attachment)
            {
                try
                {
                    if (!String.IsNullOrWhiteSpace(attachData.ReferenceUrl))
                    {
                        var attachmentFile = await WindowsPhoneUtils.GetFileFromReferenceURL(attachData.ReferenceUrl);
                        if (attachmentFile != null)
                        {
                            multipartFormDataContent.Add(new HttpStreamContent(await attachmentFile.OpenReadAsync()), attachData.FormFieldKey, attachData.FileName ?? attachmentFile.Name);
                        }
                        else
                        {
                            WindowsPhoneUtils.Log("**** [MULTIPART_FORM_DATA]. # File from referenced URL: " + attachData.ReferenceUrl + ", does not exists in filesystem, please check provided ReferenceUrl!");
                        }
                    }
                    else
                    {
                        WindowsPhoneUtils.Log("**** [MULTIPART_FORM_DATA]. # Attached file does not contain a valid ReferenceUrl field. IGNORED");
                    }
                }
                catch (Exception ex)
                {
                    WindowsPhoneUtils.Log(ex.Message);
                }
            }
            return webRequest;
        }
Ejemplo n.º 52
0
        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());
            }

        }
Ejemplo n.º 53
0
        private async void loginRequestUser(string username, string password, string url, string type)
        {
            var filter = new HttpBaseProtocolFilter();
            Uri uristringLogin = new Uri(url + "/api2/" + type + "/");     

            // *******************
            // IGNORING CERTIFACTE PROBLEMS
            // *******************
            filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.IncompleteChain);
            filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Expired);
            filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
            filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName);

            var HttpClientLogin = new HttpClient(filter);
            HttpMultipartFormDataContent requestContentLogin = new HttpMultipartFormDataContent();
            var nameHelper = new AssemblyName(Assembly.GetExecutingAssembly().FullName);

            HttpClientLogin.DefaultRequestHeaders.Add("Accept", "application/json;indent=4");
            HttpClientLogin.DefaultRequestHeaders.Add("User-agent", "CloudWave for Seafile/" + nameHelper.Version);

            var values = new[]
                    {
                        new KeyValuePair<string, string>("username", username),
                        new KeyValuePair<string, string>("password", password)
                    };

            foreach (var keyValuePair in values)
            {
                requestContentLogin.Add(new HttpStringContent(keyValuePair.Value), keyValuePair.Key);
            }

            try
            {
                HttpResponseMessage responseLogin = await HttpClientLogin.PostAsync(uristringLogin, requestContentLogin);
                responseLogin.EnsureSuccessStatusCode();

                loginDoLogin(responseLogin.Content.ToString());

                HttpClientLogin.Dispose();
            }
            catch (Exception ex)
            {
                if (GlobalVariables.IsDebugMode == true)
                {
                    App.logger.log(LogLevel.critical, "Error login : "******"URL login : "******"Please verify connection information.";

                SetProgressIndicator(false);
            }
        }
Ejemplo n.º 54
0
       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();
       
       
       
       
       }
Ejemplo n.º 55
0
        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 "";
            }


        }