Exemplo n.º 1
7
        static async void upload_image(string path)
        {
            Console.WriteLine("Uploading {0}", path);
            try {
                using (var client = new HttpClient()) {
                    using (var stream = File.OpenRead(path)) {
                        var content = new MultipartFormDataContent();
                        var file_content = new ByteArrayContent(new StreamContent(stream).ReadAsByteArrayAsync().Result);
                        file_content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
                        file_content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                        {
                            FileName = "screenshot.png",
                            Name = "foo",
                        };
                        content.Add(file_content);
                        client.BaseAddress = new Uri("https://pajlada.se/poe/imgup/");
                        var response = await client.PostAsync("upload.php", content);
                        response.EnsureSuccessStatusCode();
                        Console.WriteLine("Done");
                    }
                }

            } catch (Exception) {
                Console.WriteLine("Something went wrong while uploading the image");
            }
        }
Exemplo n.º 2
0
        public string SendAddressesToApi(string csvPath)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(CensusBatchGeoCodeUri);
                var content = new MultipartFormDataContent();

                var fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes("addresses.csv"));
                fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
                {
                    Name = "addressFile",
                    FileName = "addresses.csv"
                };
                fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                content.Add(fileContent);

                // Not a FormUrlEncodedContent class due to an ostensible bug in census API that
                // rejects key/value formatting and requires 'benchmark' in a 'name' field
                var benchMarkContent = new StringContent("9");
                benchMarkContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
                {
                    Name = "benchmark"
                };
                content.Add(benchMarkContent);

                var result = client.PostAsync("", content).Result;
                string resultContent = result.Content.ReadAsStringAsync().Result;
                return resultContent;
            }
        }
Exemplo n.º 3
0
        public void CreateBlob(Guid id, byte[] content, string fileName)
        {
            var bytes = new ByteArrayContent(content);
            bytes.Headers.ContentDisposition = new ContentDispositionHeaderValue("file") { FileName = fileName };
            bytes.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

            var request = new HttpRequestMessage(HttpMethod.Post, String.Format("/blobs/{0}", id)) { Content = bytes };

            var response = _httpClient.SendAsync(request);

            try
            {
                var result = response.Result;
                var statusCode = result.StatusCode;
                if (statusCode == HttpStatusCode.Created)
                {
                    return;
                }

                RaiseResponseError(request, result);
            }
            finally
            {
                Dispose(request, response);
            }
        }
Exemplo n.º 4
0
        public void ContentLength_UsePartialSourceArray_LengthMatchesArrayLength()
        {
            var contentData = new byte[10];
            var content = new ByteArrayContent(contentData, 5, 3);

            Assert.Equal(3, content.Headers.ContentLength);
        }
Exemplo n.º 5
0
        public void ContentLength_UseWholeSourceArray_LengthMatchesArrayLength()
        {
            var contentData = new byte[10];
            var content = new ByteArrayContent(contentData);

            Assert.Equal(contentData.Length, content.Headers.ContentLength);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Create Multipart form-data HTTP Post to upload file to S3.
        /// </summary>
        /// <param name="s3Bucket">The Amazon S3 bucket name.</param>
        /// <param name="formData">The JSON object containing the pre-signed URL data.</param>
        /// <param name="mimeType">The MIME type of the file to be uploaded.</param>
        /// <param name="compressedFile">The gzipped file contents.</param>
        /// <returns>BlipResponse object with a status code and body text if applicable.</returns>
        private static BlipResponse PostFile(string s3Bucket, string formData, string mimeType, byte[] compressedFile)
        {
            HttpResponseMessage response;
            dynamic data = JsonConvert.DeserializeObject(formData);

            using (var client = new HttpClient())
            {
                var url = $"https://s3.amazonaws.com/{s3Bucket}";
                var requestContent = new MultipartFormDataContent();
                var fileContent = new ByteArrayContent(compressedFile);
                fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse(mimeType);
                
                // Special parsing required due to a hyphen in the key
                string contentMd5 = JObject.Parse(data.ToString())["content-md5"];

                requestContent.Add(new StringContent(data.acl.ToString()), "acl");
                requestContent.Add(new StringContent(data.bucket.ToString()), "bucket");
                requestContent.Add(new StringContent(data.key.ToString()), "key");
                requestContent.Add(new StringContent(contentMd5), "content-md5");
                requestContent.Add(new StringContent(data.policy.ToString()), "policy");
                requestContent.Add(new StringContent(data.signature.ToString()), "signature");
                requestContent.Add(new StringContent(data.AWSAccessKeyId.ToString()), "AWSAccessKeyId");
                requestContent.Add(new StringContent(mimeType), "content-type");
                requestContent.Add(fileContent, "file"); // The file must be added last
                
                response = client.PostAsync(url, requestContent).Result;
            }

            var statusCode = (int)response.StatusCode;

            // If the upload is not successful return the error message from S3 else return success response
            return statusCode != 204 ? new BlipResponse(statusCode, response.Content.ToString()) : new BlipResponse(statusCode, "");
        }
        protected override HttpRequestMessage BuildMessage(IRestRequest request)
        {
            // Create message content
            var content = new MultipartFormDataContent();
            foreach (var param in request.Parameters) {
                var file = param.Value as FileParameter;

                if (file != null) {
                    var contentPart = new ByteArrayContent(file.Content);
                    contentPart.Headers.Add("Content-Type", file.ContentType);
                    content.Add(contentPart, param.Key, file.Name);
                }
                else {
                    var contentPart = new StringContent(param.Value.ToString());
                    content.Add(contentPart, param.Key);
                }
            }

            // Build message
            var message = new HttpRequestMessage(request.Verb.ToHttpMethod(), request.Command) {
                Content = content
            };

            return message;
        }
        public async Task<bool> UploadBytes(string url, byte[] data)
        {
            try
            {
                if (_networkInformation.QuickNetworkCheck())
                {
                    var native = new NativeMessageHandler();

                    var httpClient = new HttpClient(native);
                    var message = new HttpRequestMessage(HttpMethod.Post, url);

                    native.RegisterForProgress(message, (bytes, totalBytes, expected) => new TransferProgressMessage(url, bytes, totalBytes, expected, true).Send());

                    var content = new ByteArrayContent(data);

                    message.Content = content;

                    var result = await httpClient.SendAsync(message);
                    return result.IsSuccessStatusCode;
                }
            }
            catch
            {
                Debug.WriteLine("WARNING: Could not upload: {0}", url);
            }

            return false;
        }
Exemplo n.º 9
0
        /// <summary>
        /// Assincronouslly send the fields in the list to webServer in url parameter
        /// NextStep: add a percentage of uploaded data!
        /// </summary>
        /// <param name="fields"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        internal static async Task<string> send(List<field> fields, string url)
        {
            HttpClient httpClient = new HttpClient();
            MultipartFormDataContent form = new MultipartFormDataContent();

            foreach(field f in fields)
            {
                if(f.kind == fieldKind.text)
                {
                    form.Add(new StringContent(f.content), f.name);
                }
                else if (f.kind == fieldKind.file)
                {
                    HttpContent content = new ByteArrayContent(f.bytes);
                    content.Headers.Add("Content-Type", f.contentType);
                    form.Add(content, f.name, f.fileName);
                }
            }

            HttpResponseMessage response = await httpClient.PostAsync(url, form);

            response.EnsureSuccessStatusCode();
            httpClient.Dispose();
            return response.Content.ReadAsStringAsync().Result;
        }
        private static void SendImageSet(ImageSet imageSet)
        {
            var multipartContent = new MultipartFormDataContent();

            var imageSetJson = JsonConvert.SerializeObject(imageSet,
                new JsonSerializerSettings
                {
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                });

            multipartContent.Add(new StringContent(imageSetJson, Encoding.UTF8, "application/json"), "imageset");

            int counter = 0;
            foreach (var image in imageSet.Images)
            {
                var imageContent = new ByteArrayContent(image.ImageData);
                imageContent.Headers.ContentType = new MediaTypeHeaderValue(image.MimeType);
                multipartContent.Add(imageContent, "image" + counter++, image.FileName);
            }

            var response = new HttpClient()
                .PostAsync("http://localhost:53908/api/send", multipartContent)
                .Result;

            var responseContent = response.Content.ReadAsStringAsync().Result;
            Trace.Write(responseContent);
        }
Exemplo n.º 11
0
        private static void Request_POST <T>(string url, string timeKey, T data)
        {
            System.Threading.Thread th = new System.Threading.Thread(new System.Threading.ThreadStart(async() =>
            {
                using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient())
                {
                    //특정 'Accept' 헤더를 BSON으로 지정: 서버에서 BSON 형식으로 데이터를 반환하도록 요청
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(
                        new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/bson"));

                    //'Content-Type' 헤더 지정: 서버에서 게시할 데이터 형식 지정
                    //Post 데이터는 Bson 형식으로 표시됨
                    var bSonData         = SerializeBson <T>(data);
                    var byteArrayContent = new System.Net.Http.ByteArrayContent(bSonData);
                    byteArrayContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/bson");

                    await client.PostAsync(url, byteArrayContent).ContinueWith(responseTask =>
                    {
                        dicResult.Add(timeKey, responseTask.Result.ToString());
                    });
                }
            }))
            {
                IsBackground = true
            };
            th.Start();
        }
        public async Task<string> CreatePageForIncidentAsync(string siteRootDirectory, string sectionId, Incident incident, IEnumerable<FileContent> inspectionPhotos, IEnumerable<Video> incidentVideos)
        {
            var templateFile = Path.Combine(siteRootDirectory, @"Templates\IncidentOneNotePage.cshtml");
            var template = System.IO.File.ReadAllText(templateFile);
            var viewBag = new RazorEngine.Templating.DynamicViewBag();
            viewBag.AddValue("InspectionPhotos", inspectionPhotos);
            viewBag.AddValue("IncidentVideos", incidentVideos);

            var html = RazorEngine.Engine.Razor.RunCompile(template, "IncidentOneNotePage", typeof(Incident), incident, viewBag);
            var content = new MultipartFormDataContent();
            content.Add(new StringContent(html, Encoding.UTF8, "text/html"), "Presentation");

            foreach (var image in inspectionPhotos)
            {
                var itemContent = new ByteArrayContent(image.Bytes);
                var contentType = MimeMapping.GetMimeMapping(image.Name);
                itemContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
                content.Add(itemContent, image.Id);
            }

            this.pageEndPoint = string.Format("{0}/sections/{1}/pages", serviceBaseUrl, sectionId);
            var requestMessage = new HttpRequestMessage(HttpMethod.Post, pageEndPoint);
            requestMessage.Content = content;

            var responseMessage = await HttpSendAsync(requestMessage, accessToken);
            if (responseMessage.StatusCode != System.Net.HttpStatusCode.Created)
                throw new HttpResponseException(responseMessage.StatusCode);

            var reponseObject = await GetReponseObjectAsync(responseMessage);
            return (string)reponseObject.links.oneNoteWebUrl.href;
        }
        public async Task<bool> UploadBytes(string url, byte[] data)
        {
            try
            {
                if (_networkInformation.QuickNetworkCheck())
                {
                    var h = new NativeMessageHandler();
                
                    var httpClient = new HttpClient(h);
                    var message = new HttpRequestMessage(HttpMethod.Post, url);

                    var content = new ByteArrayContent(data);

                    message.Content = content;

                    var result = await httpClient.SendAsync(message);
                    return result.IsSuccessStatusCode;
                }
            }
            catch
            {
                Debug.WriteLine("WARNING: Could not upload: {0}", url);
            }

            return false;
        }
        ///// <summary>
        ///// 
        ///// </summary>
        ///// <param name="actContext"></param>
        //public override void OnActionExecuted(HttpActionExecutedContext actContext)
        //{
        //    var content = actContext.Response.Content;
        //    if (content != null)
        //    {
        //        string encoding = null;
        //        CompressionType compressionType = GetCompressionType(actContext.Request, out encoding);
        //        if (compressionType != CompressionType.None)
        //        {
        //            var bytes = content.ReadAsByteArrayAsync().Result;
        //            if (bytes != null)
        //            {
        //                byte[] zlibbedContent = null;
        //                zlibbedContent = CompressionHelper.CompressionByte(bytes, compressionType);
        //                var newContent = new ByteArrayContent(zlibbedContent);
        //                newContent.Headers.Add("Content-encoding", encoding);
        //                newContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(content.Headers.ContentType.MediaType);

        //                actContext.Response.Content = newContent;
        //            }
        //        }

        //    }

        //    base.OnActionExecuted(actContext);
        //}

        /// <summary>
        /// 
        /// </summary>
        /// <param name="actionExecutedContext"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public override async Task OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
        {
            var content = actionExecutedContext.Response.Content;
            if (content != null)
            {
                string encoding = null;
                CompressionType compressionType = GetCompressionType(actionExecutedContext.Request, out encoding);
                if (compressionType != CompressionType.None)
                {
                    var bytes = content.ReadAsByteArrayAsync().Result;
                    if (bytes != null)
                    {
                        byte[] zlibbedContent = null;
                        zlibbedContent = await CompressionHelper.CompressionByteAsync(bytes, compressionType);
                        var newContent = new ByteArrayContent(zlibbedContent);
                        newContent.Headers.Add("Content-encoding", encoding);
                        newContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(content.Headers.ContentType.MediaType);

                        actionExecutedContext.Response.Content = newContent;
                    }
                }

            }
            await base.OnActionExecutedAsync(actionExecutedContext, cancellationToken);
        }
Exemplo n.º 15
0
        public async Task Handle200AndContentType()
        {
            // Arrange
            JToken root = null;
            var machine = new HttpResponseMachine();

            machine.When(HttpStatusCode.OK, null, new MediaTypeHeaderValue("application/json"))
                .Then(async (l, r) =>
            {
                var text = await r.Content.ReadAsStringAsync();
                root = JToken.Parse(text);
            });

            machine.When(HttpStatusCode.OK, null, new MediaTypeHeaderValue("application/xml"))
                .Then(async (l, r) => { });

            var byteArrayContent = new ByteArrayContent(Encoding.UTF8.GetBytes("{\"hello\" : \"world\"}"));
            byteArrayContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            
            // Act
            await machine.HandleResponseAsync("", new HttpResponseMessage(HttpStatusCode.OK) { Content = byteArrayContent});

            // Assert
            Assert.NotNull(root);
        }
        public void Ctor()
        {
            byte[] b = { 4, 6 };

            using (var m = new ByteArrayContent (b)) {
            }
        }
        static void Main(string[] args)
        {
            string url = "http://*****:*****@"D:\GraduationMusic\ATsednya\Tsedenia GM - Atalay.mp3";

            MemoryStream requestStream = new MemoryStream();
            Stream fileStream = File.Open(path, FileMode.Open);

            var byteFile = ReadFully(fileStream);

            var base64Doc = Convert.ToBase64String(byteFile);

            HttpContent content = new ByteArrayContent(byteFile);

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(url);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                // New code:
                HttpResponseMessage response = client.PostAsync("api/trackdata/file", content).Result;

                var result = response.Content;

            }
        }
Exemplo n.º 18
0
        private async static Task<bool> SendMessageWithImageAsync(string message, string chatId, string messageId,
            Stream imageStream)
        {
            var tghttpClient = new HttpClient();
            imageStream.Seek(0, SeekOrigin.Begin);
            var buf = ReadFully(imageStream);

            var imageContent = new ByteArrayContent(buf);
            imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/png");

            // Send Message, as well as image
            var endpointUrl =
                        new Uri(string.Format(RequestTemplate.RpcOpUrl, RequestTemplate.AppId, "sendPhoto"));
            var content = new MultipartFormDataContent();
            /*content.Add(new FormUrlEncodedContent(new List<KeyValuePair<string,string>>
            {
                new KeyValuePair<string, string>("chat_id", chatId),
                new KeyValuePair<string, string>("reply_to_message_id", messageId),
                new KeyValuePair<string, string>("caption", message)
            }));*/
            content.Add(imageContent, "photo", string.Format("{0}.png", Guid.NewGuid()));
            content.Add(new ByteArrayContent(Encoding.UTF8.GetBytes(chatId)),"chat_id");
            content.Add(new ByteArrayContent(Encoding.UTF8.GetBytes(messageId)), "reply_to_message_id");
            content.Add(new ByteArrayContent(Encoding.UTF8.GetBytes(message)), "aptiond");
            var result = await
                tghttpClient.PostAsync(endpointUrl, content);
            var content2 = await result.Content.ReadAsStringAsync();
            return result.IsSuccessStatusCode;
        }
 public ElasticsearchResponse DoSyncRequest(string method, Uri uri, byte[] data = null)
 {
     var client = new System.Net.Http.HttpClient();
     HttpResponseMessage response = null;
     byte[] result = null;
     HttpContent content = null;
     if (data != null)
         content = new ByteArrayContent(data);
     switch (method.ToLower())
     {
         case "head":
             response = client.SendAsync(new HttpRequestMessage(HttpMethod.Head, uri) ).Result;
             result = response.Content.ReadAsByteArrayAsync().Result;
             break;
         case "delete":
             response = client.SendAsync(new HttpRequestMessage(HttpMethod.Delete, uri) { Content = content }).Result;
             result = response.Content.ReadAsByteArrayAsync().Result;
             break;
         case "put":
             response = client.PutAsync(uri, content).Result;
             result = response.Content.ReadAsByteArrayAsync().Result;
             break;
         case "post":
             response = client.PostAsync(uri, content).Result;
             result = response.Content.ReadAsByteArrayAsync().Result;
             break;
         case "get":
             response = client.GetAsync(uri).Result;
             result = response.Content.ReadAsByteArrayAsync().Result;
             break;
     }
     return ElasticsearchResponse.Create(this._settings, (int)response.StatusCode, method, uri.ToString(), data, result);
 }
Exemplo n.º 20
0
        public async Task<HttpResponseMessage> GetImage(string name)
        {
            var userEmails = await UsersForHub();
            if (userEmails == null)
            {
                Services.Log.Error("No logged in user", null, "SetupToken");
                return new HttpResponseMessage(HttpStatusCode.Unauthorized);
            }

            byte[] imageBytes = null;
            foreach (var email in userEmails)
            {
                if (imageBytes == null)
                {
                    imageBytes = await GetStatusImageBytesForUser(email, name);
                }
            }

            if (imageBytes != null)
            {
                var content = new ByteArrayContent(imageBytes);
                content.Headers.ContentType = new MediaTypeHeaderValue("image/png");

                return new HttpResponseMessage(HttpStatusCode.OK) { Content = content };
            }
            else
            {
                Services.Log.Error(string.Format("Status image {0} not found", name));
                return new HttpResponseMessage(HttpStatusCode.NotFound);
            }
        }
        public void Should_Accept_Only_Text_Content()
        {
            // Arrange
            Mock<IStorageRepository> storageRepositoryMock;
            Mock<IFileProcessor> fileProcessorMock;
            Mock<IChecksumCalculator> checksumCalculatorMock;
            Mock<IMetadataRepository> metadataRepositoryMock;
            var controller = this.ConfigureController(out storageRepositoryMock, out fileProcessorMock, out checksumCalculatorMock, out metadataRepositoryMock);

            var multipartContent = new MultipartFormDataContent();
            var binaryContent = Enumerable.Repeat(Enumerable.Range(14, 255).ToArray(), 20).SelectMany(x => x.Select(y => y)).Select(x=>(byte)x).ToArray();
            var fileContent = new ByteArrayContent(binaryContent);
            fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = "Test.txt" };
            fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("something/that_we_dont_expect");
            multipartContent.Add(fileContent);
            controller.Request.Content = multipartContent;

            // Act
            Task<IHttpActionResult> task = controller.Post();
            task.Wait();

            // Assert
            GenericValueResult<List<MetadataInfo>> result = task.Result as GenericValueResult<List<MetadataInfo>>;
            result.Should().NotBeNull("Wrong data type was returned from the controller");

            var t = result.Value as IEnumerable<Models.MetadataInfo>;
            t.Should().NotBeNull("Wrong data type was returned as a result of controller's work");

            var informationFromService = t.First();
            informationFromService.Id.Should().NotHaveValue();
            informationFromService.ProcessingResult.Should().Be(UploadController.ContentTypeCannotBeAcceptedMessage);
        }
Exemplo n.º 22
0
        private async Task ForwardToModBusProtocolAdapterAsync(byte[] message)
        {
            try
            {
                HttpContent content = new System.Net.Http.ByteArrayContent(message);
                content.Headers.ContentType   = new MediaTypeHeaderValue(Constants.CONTENT_TYPE);
                content.Headers.ContentLength = message.Length;
                string requestUrl            = IPHelper.GetAddress();
                HttpResponseMessage response = await httpClient.PostAsync(requestUrl, content);

                Console.WriteLine("{0} - Forwarded msg to PA with status code '{1}'", DateTime.Now.ToString("hh:MM:ss.ffff"), response.StatusCode);
            }
            catch (WebException we)
            {
                Console.WriteLine("Web exception - {0}", we.Message);
                if (we.InnerException != null)
                {
                    Console.WriteLine("Web inner exception - {0}", we.InnerException.Message);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Post exception - {0}", ex.Message);
                if (ex.InnerException != null)
                {
                    Console.WriteLine("Post inner exception - {0}", ex.InnerException.Message);
                }
            }
        }
Exemplo n.º 23
0
        public async Task<string> SendRaw(string uri, byte[] json)
        {
            System.Net.Http.HttpClient http = new System.Net.Http.HttpClient();

            var content = new ByteArrayContent(json);
            var response = await http.PostAsync(Host + uri, content);

            return await response.Content.ReadAsStringAsync();
        }
        public override HttpContent GetContent(HttpRequestParams parameters)
        {
            var resource = PrepareResource();

            var content = new ByteArrayContent(resource);
            content.Headers.ContentType = new MediaTypeHeaderValue(contentType);

            return content;
        }
        internal override HttpContent AsHttpContent()
        {
            var content = new MultipartFormDataContent();
            var bytesContent = new ByteArrayContent(ContentBytes);
            bytesContent.Headers.ContentType = MediaTypeHeaderValue.Parse(ContentType);

            content.Add(bytesContent, Name, FileName);
            return content;
        }
Exemplo n.º 26
0
 public JsonHttpResponseMessage(HttpStatusCode responceStatusCode, Type responseDataType, object responseData)
 {
     StatusCode = responceStatusCode;
     dynamic convertedResponceData = Convert.ChangeType(responseData, responseDataType);
     var jss = new JavaScriptSerializer();
     var encoder = new ASCIIEncoding();
     Content = new ByteArrayContent(encoder.GetBytes(jss.Serialize(convertedResponceData)));
     Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
 }
Exemplo n.º 27
0
        public IObservable<HttpResponseMessage> GetResponse()
        {
            var addParam = new ParameterCollection();
            var requestMessage = new HttpRequestMessage(_Method, _Endpoint);
            NetworkSettings.GetOptionRequestHeaders.Select(p => { requestMessage.Headers.Add(p.Key, p.Value); return p; });

            if (_Method == HttpMethod.Get)
            {
                var requestUri = _Endpoint;
                var uriParameter = _ParameterCollection.ToUrlParameter();
                if (uriParameter.Length > 0)
                {
                    requestUri += "?" + uriParameter;
                }

                requestMessage.RequestUri = new Uri(requestUri);
                addParam = _ParameterCollection;
            }
            else if (_Method == HttpMethod.Post)
            {
                switch (_ContentType)
                {
                    case ContentType.FormUrlEncoded:
                        requestMessage.Content = new FormUrlEncodedContent(_ParameterCollection.Where(p => p.Value != null).Select(p => new KeyValuePair<string, string>(p.Name, p.Value.ToString())));
                        addParam = _ParameterCollection;
                        break;

                    case ContentType.MultipartFormData:
                        requestMessage.Content = _ParameterCollection.Where(p => p.Value != null).Aggregate(new MultipartFormDataContent(), (c, p) =>
                        {
                            if (p.FileName == null)
                            {
                                var sc = new StringContent(p.Value.ToString());
                                c.Add(sc, "\"" + p.Name + "\""); // TODO: ""を自分で付け加えないとname=statusとなってしまい無視されてしまう/あとでよく調べる必要あり
                            }
                            else
                            {
                                var bac = new ByteArrayContent((byte[])p.Value);
                                c.Add(bac, p.Name, "\"" + p.FileName + "\"");
                            }
                            return c;
                        });
                        break;
                }
            }

            var handler = new HttpClientHandler();
            handler.UseProxy = NetworkSettings.Proxy != null;
            handler.Proxy = NetworkSettings.Proxy;
            var client = new HttpClient(new OAuthMessageHandler(_Consumer, _OAuthToken, _Realm, addParam, handler));
            client.Timeout = NetworkSettings.Timeout;

            return client
                .SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead)
                .ToObservable();
        }
Exemplo n.º 28
0
        /// <summary>
        /// Uploads an activity.
        /// </summary>
        /// <param name="file">The path to the activity file on your local hard disk.</param>
        /// <param name="dataFormat">The format of the file.</param>
        /// <param name="activityType">The type of the activity.</param>
        /// <returns>The status of the upload.</returns>
        public async Task<UploadStatus> UploadActivityAsync(StorageFile file, DataFormat dataFormat, ActivityType activityType = ActivityType.Ride)
        {
            String format = String.Empty;

            switch (dataFormat)
            {
                case DataFormat.Fit:
                    format = "fit";
                    break;
                case DataFormat.FitGZipped:
                    format = "fit.gz";
                    break;
                case DataFormat.Gpx:
                    format = "gpx";
                    break;
                case DataFormat.GpxGZipped:
                    format = "gpx.gz";
                    break;
                case DataFormat.Tcx:
                    format = "tcx";
                    break;
                case DataFormat.TcxGZipped:
                    format = "tcx.gz";
                    break;
            }
           
            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Add("Authorization", String.Format("Bearer {0}", Authentication.AccessToken));

            MultipartFormDataContent content = new MultipartFormDataContent();

            byte[] fileBytes = null;
            using (IRandomAccessStreamWithContentType stream = await file.OpenReadAsync())
            {
                fileBytes = new byte[stream.Size];
                using (DataReader reader = new DataReader(stream))
                {
                    await reader.LoadAsync((uint)stream.Size);
                    reader.ReadBytes(fileBytes);
                }
            }

            var byteArrayContent = new ByteArrayContent(fileBytes);

            content.Add(byteArrayContent, "file", file.Name);

            HttpResponseMessage result = await client.PostAsync(
                String.Format("https://www.strava.com/api/v3/uploads?data_type={0}&activity_type={1}",
                format,
                activityType.ToString().ToLower()),
                content);

            String json = await result.Content.ReadAsStringAsync();

            return Unmarshaller<UploadStatus>.Unmarshal(json);
        }
Exemplo n.º 29
0
        public async Task<HttpResponseMessage> PostAsync(string requestUrl, byte[] requestData)
        {
            var content = new ByteArrayContent(requestData);
            content.Headers.ContentLength = requestData.Length;

            using (var client = new HttpClient())
            {
                return await client.PutAsync(requestUrl, content);
            }
        }
Exemplo n.º 30
0
        public static async Task<HttpContent> Clone(this HttpContent source)
        {
            if (source == null)
                return null;

            await source.LoadIntoBufferAsync();
            var destination = new ByteArrayContent(await source.ReadAsByteArrayAsync());
            CopyHeadersFrom(destination.Headers, source.Headers);
            return destination;
        }
Exemplo n.º 31
0
        public async Task<HttpResponseMessage> PostAsync(Uri uri, Dictionary<string, string> fields, string fileName, byte[] imageData)
        {
            ByteArrayContent file = new ByteArrayContent(imageData);

            MultipartFormDataContent form = new MultipartFormDataContent();
            foreach (KeyValuePair<string, string> field in fields) form.Add(new StringContent(field.Value), "\"" + field.Key + "\"");
            form.Add(file, "\"upfile\"", "\"" + fileName + "\"");

            return await _client.PostAsync(EnforceHTTPS(uri), form);
        }
Exemplo n.º 32
0
 public async Task<string> Send(User U)
 {
     await U.SetBaseAddress();
         ByteArrayContent C = new ByteArrayContent(Crypto.EncryptRequest(this));
         C.Headers.Add("soapaction", "\"" + SoapAction + "\"");
         C.Headers.Add("content-type", "text/xml; charset=utf-8");
         var Req = await U._client.PostAsync(String.Format("{0}Service.svc", this.Service), C);
         var ba = await Req.Content.ReadAsByteArrayAsync();
         return Crypto.DecryptResponse(ba);
 }
Exemplo n.º 33
0
        /* Responsible for creating a request of the specified type. Used
         * only during POST and PUT since it requires a payload to be provided.
         */
        async Task <Response <TOut> > CreateContentRequest <TOut>(
            string url,
            net.HttpMethod method,
            object input,
            Dictionary <string, string> headers)
        {
            using (var msg = CreateRequestMessage(method, url, headers))
            {
                if (input is Stream stream)
                {
                    using (var content = new net.StreamContent(stream))
                    {
                        AddContentHeaders(content, headers);
                        msg.Content = content;
                        return(await GetResult <TOut>(msg));
                    }
                }
                else if (input is byte[] bytes)
                {
                    using (var content = new net.ByteArrayContent(bytes))
                    {
                        AddContentHeaders(content, headers);
                        msg.Content = content;
                        return(await GetResult <TOut>(msg));
                    }
                }

                var stringContent = input is string strInput ?
                                    strInput :
                                    JObject.FromObject(input).ToString();

                using (var content = new net.StringContent(stringContent))
                {
                    AddContentHeaders(content, headers);
                    msg.Content = content;
                    return(await GetResult <TOut>(msg));
                }
            }
        }
Exemplo n.º 34
0
 public BinaryContent(Http.ByteArrayContent content)
     : base(content)
 {
 }
Exemplo n.º 35
0
        public static async Task <string> HttpClientPostAsync2(string url, Dictionary <string, object> Headerdics, byte[] postdata, string datatype, CookieContainer cookieContainers, string redirecturl)
        {
            if (string.IsNullOrEmpty(url))
            {
                return("");
            }
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11;
            ServicePointManager.ServerCertificateValidationCallback = (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) =>
            {
                return(true);
            };
            var res = "";

            try
            {
                using (var handler = new HttpClientHandler())
                {
                    handler.CookieContainer = cookieContainers;
                    using (var client = new HttpClient(handler))
                    {
                        foreach (var pair in Headerdics)
                        {
                            client.DefaultRequestHeaders.TryAddWithoutValidation(pair.Key, (string)pair.Value);
                        }
                        System.Net.Http.ByteArrayContent content = new System.Net.Http.ByteArrayContent(postdata);
                        using (HttpResponseMessage HttpResponse = await client.PostAsync(url, content))
                        {
                            HttpResponse.EnsureSuccessStatusCode();
                            if (HttpResponse.Headers.Location != null)
                            {
                                redirecturl = HttpResponse.Headers.Location.ToString();
                            }
                            if (HttpResponse.ToString().ToLower().Contains("gzip"))
                            {
                                using (Stream HttpResponseStream = await client.GetStreamAsync(url))
                                {
                                    using (var gzipStream = new GZipStream(HttpResponseStream, CompressionMode.Decompress))
                                    {
                                        using (var streamReader = new StreamReader(gzipStream, Encoding.UTF8))
                                        {
                                            res = streamReader.ReadToEnd();
                                        }
                                    }
                                }
                            }
                            else
                            {
                                using (HttpContent HttpContent = HttpResponse.Content)
                                {
                                    res = await HttpContent.ReadAsStringAsync();
                                }
                            }
                        }
                    }
                }
            }
            catch (WebException e)
            {
                using (WebResponse response = e.Response)
                {
                    HttpWebResponse httpResponse = (HttpWebResponse)response;
                    Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
                    using (Stream data = response.GetResponseStream())
                    {
                        using (var reader = new StreamReader(data))
                        {
                            res = reader.ReadToEnd();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    Debug.Print(ex.GetBaseException().Message.ToString());
                }
                else
                {
                    Debug.Print(ex.Message.ToString());
                }
            }

            return(res);
        }
Exemplo n.º 36
0
        //Envoi de flux livraison à Mroad
        public static async Task <HttpResponseMessage> SendData(List <TournesValidesToAkanea> tournesValidesToAkanea, string intervention)
        {
            TimeSpan            timeout  = new TimeSpan(0, 0, 30);
            HttpResponseMessage response = null;

            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri("https://1807-tms-messagerie.akanea.com/json/");
                string accessId = "VIRTRP";
                string userId   = "VIRAPI";
                string password = "******";
                string token    = null;

                Task <System.Net.Http.HttpResponseMessage> taskRetour = client.GetAsync($"Login/GetToken?accessId={accessId}&userId={userId}&password={password}");
                taskRetour.Wait();

                using (response = taskRetour.Result)
                {
                    Task <string> task2 = response.Content.ReadAsStringAsync();
                    token = JsonConvert.DeserializeObject <string>(task2.Result);
                    logger.Info($"Token gotten from Akanea : {token}");
                    response.EnsureSuccessStatusCode();
                }

                try
                {
                    // pour l'exemple
                    //  object bordereaux = null;
                    List <TournesValidesToAkanea> bordereaux = tournesValidesToAkanea;

                    var ss = JsonConvert.SerializeObject(bordereaux);
                    logger.Info(string.Format("{0} => {1}", "json to Akanea", ss));
                    byte[] datas = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(bordereaux));

                    using (System.Net.Http.HttpContent byteContent = new System.Net.Http.ByteArrayContent(datas))
                    {
                        byteContent.Headers.ContentType   = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                        byteContent.Headers.ContentLength = datas.Length;
                        logger.Info($"Envoi vers Akanea : {"https://1807-tms-messagerie.akanea.com/json/"}{intervention}?token={token}");
                        taskRetour = client.PostAsync($"{intervention}?token={token}", byteContent);
                        taskRetour.Wait();

                        using (response = taskRetour.Result)
                        {
                            Task <string> task2   = response.Content.ReadAsStringAsync();
                            string        message = task2.Result;

                            logger.Info($"Retour message Akanea: {message}");

                            //  response.EnsureSuccessStatusCode();
                        }
                    }
                }
                finally
                {
                    // libération jeton
                    taskRetour = client.GetAsync($"Login/ReleaseToken?token={token}");

                    using (response = taskRetour.Result)
                    {
                        logger.Info($"Liberation de Token : {taskRetour.Result}");
                        // response.EnsureSuccessStatusCode();
                    }
                }
            }
            return(response);
        }
        public async Task <string> HttpRequest
        (
            IElevationServiceProvider serviceProvider,
            Stack <Coordinate> coordinates,
            string apikey,
            int maxCoordinatesPerRequest,
            Ticket ticket,
            bool logTraffic
        )
        {
            //assertions:
            if (coordinates.Count == 0)
            {
                Debug.LogWarning("coordinates.Count is 0");
                return(null);
            }

            //
            List <Coordinate> requestList = new List <Coordinate>();
            //const int lengthLimit = 102375;//(bytes) this number is guesstimation, i found errors but no documentation on this
            int limit = maxCoordinatesPerRequest;//2200;//guesstimation

            for (int i = 0; i < limit && coordinates.Count != 0; i++)
            {
                requestList.Add(coordinates.Pop());
            }

            //create the HttpContent for the form to be posted:
            System.Net.Http.ByteArrayContent requestContent = null;
            if (serviceProvider.httpMethod == HttpMethod.Post)
            {
                string json   = serviceProvider.GetRequestContent(requestList);
                byte[] buffer = System.Text.Encoding.ASCII.GetBytes(json);
                requestContent = new ByteArrayContent(buffer);
                requestContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                //Debug.Log( "requestContent.Headers.ContentLength.Value: " + requestContent.Headers.ContentLength.Value );

                //log request:
                if (logTraffic)
                {
                    Debug.Log($"requesting { requestList.Count } values:\n{ json }");
                }
            }

            //get the stream of the content.
            string result = null;

            while (result == null && ticket.valid)
            {
                try
                {
                    HttpResponseMessage response;

                    if (serviceProvider.httpMethod == HttpMethod.Post)
                    {
                        response = await _client.PostAsync(
                            serviceProvider.RequestUri(null, apikey),
                            requestContent
                            );
                    }
                    else if (serviceProvider.httpMethod == HttpMethod.Get)
                    {
                        response = await _client.GetAsync(
                            serviceProvider.RequestUri(serviceProvider.GetRequestContent(requestList), apikey)
                            );
                    }
                    else
                    {
                        throw new System.NotImplementedException();
                    }

                    result = await response.Content.ReadAsStringAsync();

                    if (result.StartsWith("<html>"))
                    {
                        const string ERROR_504 = "504 Gateway Time-out";
                        const string ERROR_502 = "502 Bad Gateway";
                        const string ERROR_500 = "500 Internal Server Error";

                        //log warning:
                        if (result.Contains(ERROR_504))
                        {
                            Debug.LogWarning(ERROR_504);
                        }
                        else if (result.Contains(ERROR_502))
                        {
                            Debug.LogWarning(ERROR_502);
                        }
                        else if (result.Contains(ERROR_500))
                        {
                            Debug.LogWarning(ERROR_500);
                        }
                        else
                        {
                            Debug.LogWarning($"invalid response:\n{ result }");
                        }

                        //invalidate:
                        result = null;

                        await Task.Delay(1000);  //try again after delay
                    }
                    else if (result.StartsWith("{\"error\": \"Invalid JSON.\"}"))
                    {
                        //log warning:
                        Debug.LogWarning($"invalid JSON. Try decreasing { nameof(maxCoordinatesPerRequest) }");

                        await Task.Delay(1000);  //try again after delay
                    }
                }
                catch (System.Net.WebException ex)
                {
                    Debug.LogException(ex);
                    await Task.Delay(1000);  //try again after delay
                }
                catch (System.Exception ex)
                {
                    Debug.LogException(ex);
                    await Task.Delay(1000);  //try again after delay
                }
            }

            //log response:
            if (logTraffic)
            {
                Debug.Log($"\tresponse:\n{ result }");
            }

            //return results:
            return(result);
        }
Exemplo n.º 38
0
        /// <summary>
        /// 上传多个二进制文件数组
        /// </summary>
        /// <param name="url"></param>
        /// <param name="bytecontentlist">文件内容数组</param>
        /// <param name="filenamelist">文件名数组(与内容的序号相同)</param>
        /// <param name="RequestParam"></param>
        /// <param name="isGet"></param>
        /// <param name="havessl"></param>
        /// <param name="HeaderParam"></param>
        /// <param name="timeOutSecond"></param>
        /// <returns></returns>
        public HttpResponseMessage upAsycHttpFile(string url, List <byte[]> bytecontentlist, List <string> filenamelist, Dictionary <string, string> RequestParam = null, bool isGet = true, bool havessl = false, Dictionary <string, string> HeaderParam = null, int timeOutSecond = -1)
        {
            HttpClient client = null;

            if (bytecontentlist.Count != filenamelist.Count)
            {
                throw new Exception("DispErr_ContentAndFilenameNotEq");
            }
            if (havessl)
            {
                client = new HttpClient();
            }
            else
            {
                client = new HttpClient();
            }

            if (timeOutSecond > 0)
            {
                client.Timeout = new TimeSpan(0, 0, timeOutSecond);
            }
            if (!string.IsNullOrEmpty(_tokenName))
            {
                client.DefaultRequestHeaders.Add(_tokenName, _token);
            }
            if (HeaderParam != null)
            {
                foreach (var key in HeaderParam.Keys)
                {
                    client.DefaultRequestHeaders.Add(key, HeaderParam[key]);
                }
            }
            //   client.DefaultRequestHeaders.Add("Content-Type", "multipart/form-data");
            MultipartFormDataContent form = new MultipartFormDataContent();

            if (RequestParam != null && RequestParam.Keys.Count > 0)
            {
                foreach (var key in RequestParam.Keys)
                {
                    //FrmLib.Log.commLoger.devLoger.InfoFormat("key:{0},vale:{1}", key, RequestParam[key]);
                    var dataContent = new ByteArrayContent(Encoding.UTF8.GetBytes(RequestParam[key]));
                    dataContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
                    {
                        Name = key
                    };
                    form.Add(dataContent);
                }
            }
            for (int i = 0; i < bytecontentlist.Count; i++)
            {
                var fileContent = new System.Net.Http.ByteArrayContent(bytecontentlist[i]);
                fileContent.Headers.ContentType        = new MediaTypeHeaderValue("application/octet-stream");
                fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
                {
                    Name = "file", FileName = "\"" + filenamelist[i] + "\""
                };
                form.Add(fileContent, "file" + i.ToString());
            }

            try
            {
                //FrmLib.Log.commLoger.devLoger.InfoFormat("now PostAsync url: " + url);
                //  var task1 = client.PostAsync(url, form);

                var task2 = client.PostAsync(url, form).Result;

                /*   (requestTask) =>
                 * {
                 *     HttpResponseMessage response = requestTask.Result;
                 *
                 *     return response;
                 *
                 * });
                 */
                return(task2);
            }
            catch (Exception ex)
            {
                string    errmessage = ex.Message;
                Exception tmpex      = ex;
                while (tmpex.InnerException != null)
                {
                    tmpex      = tmpex.InnerException;
                    errmessage = errmessage + System.Environment.NewLine
                                 + tmpex.Message;
                }

                FrmLib.Log.commLoger.runLoger.ErrorFormat("exception:" + errmessage);
                throw ex;
            }
        }