private void OnSendImage(object sender, RoutedEventArgs e) { var task = new PhotoChooserTask(); task.ShowCamera = true; task.Completed += async (s, r) => { if (r.TaskResult == TaskResult.OK) { try { var request = new HttpPostRequest("http://yourdomain.com/Upload"); request.ContentType = "multipart/form-data"; request.Data.Add("vve", "VvE Naam"); request.Files.Add(new HttpPostFile("image", "image", r.ChosenPhoto)); //// TODO: Add pr var response = await Http.PostAsync(request); MessageBox.Show(response.Response); } catch (Exception exception) { MessageBox.Show(exception.Message); } } }; task.Show(); }
public static Task <HttpResponse> Post(HttpPostRequest request, CancellationToken token, Action <HttpResponse> completed) { var task = PostAsync(request, token); task.ContinueWith(t => { if (t.Exception != null) { completed(new HttpResponse(request) { Exception = t.Exception.InnerException }); } else if (t.IsCanceled) { completed(new HttpResponse(request) { Canceled = true }); } else { completed(t.Result); } }, token); return(task); }
public static Task <HttpResponse> PostAsync(HttpPostRequest request) { var task = new TaskCompletionSource <HttpResponse>(); Post(request, result => { if (result.Successful) { task.SetResult(result); } else if (result.Canceled) { task.SetCanceled(); } else { task.SetException(result.Exception); } }); return(task.Task); }
private async void OnHttpPostRequestMyToolkit(object sender, RoutedEventArgs e) { try { var request = new HttpPostRequest(UrlBox.Text); request.Data.Add("Key1", "Value1"); //request.Files.Add(new HttpPostFile(...)); var response = await request.PostAsync(); ResponseBox.Text = response.Response; } catch (OperationCanceledException exception) { // Do nothing } catch (HttpStatusException exception) { // TODO: Handle exception } catch (Exception exception) { // TODO: Handle exception } }
private static void WritePostData(Stream stream, String boundary, HttpPostRequest request) { var boundarybytes = request.Encoding.GetBytes("\r\n--" + boundary + "\r\n"); const string dataHeaderTemplate = "Content-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}"; if (request.RawData != null) { throw new Exception("RawData not allowed if uploading files"); } foreach (var tuple in request.Data) { stream.Write(boundarybytes, 0, boundarybytes.Length); var formitem = string.Format(dataHeaderTemplate, tuple.Key, tuple.Value); var formitembytes = request.Encoding.GetBytes(formitem); stream.Write(formitembytes, 0, formitembytes.Length); } const string fileHeaderTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n"; foreach (var file in request.Files) { stream.Write(boundarybytes, 0, boundarybytes.Length); var header = string.Format(fileHeaderTemplate, file.Name, file.Filename, file.ContentType ?? "application/octet-stream"); var headerbytes = request.Encoding.GetBytes(header); stream.Write(headerbytes, 0, headerbytes.Length); var fileStream = file.Stream; #if WINRT if (fileStream == null) { var operation = file.File.OpenReadAsync(); var task = operation.AsTask(); task.RunSynchronously(); fileStream = operation.GetResults().AsStreamForRead(); } #else #if SL4 || SL5 || WP7 || WP8 if (fileStream == null) { var isf = IsolatedStorageFile.GetUserStoreForApplication(); fileStream = new IsolatedStorageFileStream(file.Path, FileMode.Open, FileAccess.Read, isf); } #else if (fileStream == null) { fileStream = new FileStream(file.Path, FileMode.Open, FileAccess.Read); } #endif #endif try { var buffer = new byte[1024]; var bytesRead = 0; while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { stream.Write(buffer, 0, bytesRead); //stream.Flush(); // TODO call progress changed event handler (calculate progress over all files) => use flush to have correct behaviour // TODO add progress for download } } finally { if (file.CloseStream) { fileStream.Dispose(); } } } boundarybytes = request.Encoding.GetBytes("\r\n--" + boundary + "--\r\n"); stream.Write(boundarybytes, 0, boundarybytes.Length); }
private static HttpResponse Post(HttpPostRequest req, Action <HttpResponse> action, string method) { var response = new HttpResponse(req); try { var boundary = ""; var request = CreateRequest(req); if (req.Credentials != null) { request.Credentials = req.Credentials; } response.WebRequest = request; if (req.Files.Count == 0) { request.ContentType = "application/x-www-form-urlencoded"; } else { boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x"); request.ContentType = "multipart/form-data; boundary=" + boundary; } if (req.Cookies.Count > 0) { request.CookieContainer = new CookieContainer(); foreach (var c in req.Cookies) { request.CookieContainer.Add(request.RequestUri, c); } } request.Method = method; if (req.ContentType != null) { request.ContentType = req.ContentType; } if (req.Headers.Count > 0) { foreach (var item in req.Headers) { request.Headers[item.Key] = item.Value; } } #if USE_GZIP if (req.RequestGzip) { request.Headers[HttpRequestHeader.AcceptEncoding] = "gzip"; } #endif response.CreateTimeoutTimer(request); request.BeginGetRequestStream(delegate(IAsyncResult ar1) { try { using (var stream = request.EndGetRequestStream(ar1)) { if (req.Files.Count > 0) { WritePostData(stream, boundary, req); } else { WritePostData(stream, req); } } request.BeginGetResponse(r => ProcessResponse(r, request, response, action), request); } catch (Exception e) { response.Exception = e; if (action != null) { action(response); } } }, request); } catch (Exception e) { response.Exception = e; if (action != null) { action(response); } } lock (pendingRequests) pendingRequests.Add(response); return(response); }
private static void WritePostData(Stream stream, HttpPostRequest request) { var bytes = request.RawData ?? request.Encoding.GetBytes(GetQueryString(request.Data)); stream.Write(bytes, 0, bytes.Length); }
public static HttpResponse Put(HttpPostRequest req, Action <HttpResponse> action) { return(Post(req, action, "PUT")); }
public static HttpResponse Delete(HttpPostRequest req, Action <HttpResponse> action) { return(Post(req, action, "DELETE")); }
public static Task <HttpResponse> Post(HttpPostRequest request, Action <HttpResponse> completed) { return(Post(request, CancellationToken.None, completed)); }
private static HttpResponse Post(HttpPostRequest req, Action<HttpResponse> action, string method) { var response = new HttpResponse(req); try { var boundary = ""; var request = CreateRequest(req); if (req.Credentials != null) request.Credentials = req.Credentials; response.WebRequest = request; if (req.Files.Count == 0) request.ContentType = "application/x-www-form-urlencoded"; else { boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x"); request.ContentType = "multipart/form-data; boundary=" + boundary; } if (req.Cookies.Count > 0) { request.CookieContainer = new CookieContainer(); foreach (var c in req.Cookies) request.CookieContainer.Add(request.RequestUri, c); } request.Method = method; if (req.ContentType != null) request.ContentType = req.ContentType; if (req.Headers.Count > 0) { foreach (var item in req.Headers) request.Headers[item.Key] = item.Value; } #if USE_GZIP if (req.RequestGzip) request.Headers[HttpRequestHeader.AcceptEncoding] = "gzip"; #endif response.CreateTimeoutTimer(request); request.BeginGetRequestStream(delegate(IAsyncResult ar1) { try { using (var stream = request.EndGetRequestStream(ar1)) { if (req.Files.Count > 0) WritePostData(stream, boundary, req); else WritePostData(stream, req); } request.BeginGetResponse(r => ProcessResponse(r, request, response, action), request); } catch (Exception e) { response.Exception = e; if (action != null) action(response); } }, request); } catch (Exception e) { response.Exception = e; if (action != null) action(response); } lock (pendingRequests) pendingRequests.Add(response); return response; }
public static Task<HttpResponse> Post(HttpPostRequest request, Action<HttpResponse> completed) { return Post(request, CancellationToken.None, completed); }
public static Task<HttpResponse> PostAsync(HttpPostRequest request) { var task = new TaskCompletionSource<HttpResponse>(); Post(request, result => { if (result.Successful) task.SetResult(result); else if (result.Canceled) task.SetCanceled(); else task.SetException(result.Exception); }); return task.Task; }
/// <summary> /// Performs a HTTP POST request. /// </summary> /// <param name="request">The <see cref="HttpPostRequest"/>. </param> /// <returns>The <see cref="HttpResponse"/>. </returns> public static Task<HttpResponse> PostAsync(HttpPostRequest request) { return PostAsync(request, CancellationToken.None); }
/// <summary> /// Performs a HTTP POST request. /// </summary> /// <param name="request">The <see cref="HttpPostRequest"/>. </param> /// <param name="token">The <see cref="CancellationToken"/>. </param> /// <param name="progress">The <see cref="IProgress{T}"/>. </param> /// <returns>The <see cref="HttpResponse"/>. </returns> public static async Task<HttpResponse> PostAsync(HttpPostRequest request, CancellationToken token, IProgress<HttpProgress> progress = null) { var uri = GetQueryString(request, request.Query); var handler = CreateHandler(request, uri); using (var client = CreateClient(request, handler)) { var result = new HttpResponse(request); result.HttpClient = client; lock (PendingRequests) PendingRequests.Add(result); try { HttpContent content = null; if (request.RawData != null) content = new ByteArrayContent(request.RawData); else if (request.Files == null || request.Files.Count == 0) content = new ByteArrayContent(request.Encoding.GetBytes(GetQueryString(request.Data))); else { var multipartContent = new MultipartFormDataContent(); foreach (var pair in request.Data) multipartContent.Add(new ByteArrayContent(request.Encoding.GetBytes(pair.Value)), pair.Key); foreach (var file in request.Files) { try { var byteContent = new ByteArrayContent(await file.Stream.ReadToEndAsync(0, token, null)); byteContent.Headers.ContentType = new MediaTypeHeaderValue( file.ContentType ?? "application/octet-stream"); multipartContent.Add(byteContent, file.Name, file.Filename); } finally { if (file.CloseStream) file.Stream.Dispose(); } } content = multipartContent; } var response = await client.PostAsync(uri, content, token); await CreateResponse(result, uri, request, handler, response, token, progress); result.HttpStatusCode = response.StatusCode; if (!response.IsSuccessStatusCode) result.Exception = new HttpStatusException(response.StatusCode.ToString()) { Result = result, HttpStatusCode = result.HttpStatusCode }; } catch (Exception ex) { if (result.Exception == null) { result.Exception = ex; throw; } } finally { lock (PendingRequests) PendingRequests.Remove(result); } if (result.Exception != null) throw result.Exception; return result; } }
public static HttpResponse Put(HttpPostRequest req, Action<HttpResponse> action) { return Post(req, action, "PUT"); }
private static void WritePostData(Stream stream, String boundary, HttpPostRequest request) { var boundarybytes = request.Encoding.GetBytes("\r\n--" + boundary + "\r\n"); const string dataHeaderTemplate = "Content-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}"; if (request.RawData != null) throw new Exception("RawData not allowed if uploading files"); foreach (var tuple in request.Data) { stream.Write(boundarybytes, 0, boundarybytes.Length); var formitem = string.Format(dataHeaderTemplate, tuple.Key, tuple.Value); var formitembytes = request.Encoding.GetBytes(formitem); stream.Write(formitembytes, 0, formitembytes.Length); } const string fileHeaderTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n"; foreach (var file in request.Files) { stream.Write(boundarybytes, 0, boundarybytes.Length); var header = string.Format(fileHeaderTemplate, file.Name, file.Filename, file.ContentType ?? "application/octet-stream"); var headerbytes = request.Encoding.GetBytes(header); stream.Write(headerbytes, 0, headerbytes.Length); var fileStream = file.Stream; #if WINRT if (fileStream == null) { var operation = file.File.OpenReadAsync(); var task = operation.AsTask(); task.RunSynchronously(); fileStream = operation.GetResults().AsStreamForRead(); } #else #if SL4 || SL5 || WP7 || WP8 if (fileStream == null) { var isf = IsolatedStorageFile.GetUserStoreForApplication(); fileStream = new IsolatedStorageFileStream(file.Path, FileMode.Open, FileAccess.Read, isf); } #else if (fileStream == null) fileStream = new FileStream(file.Path, FileMode.Open, FileAccess.Read); #endif #endif try { var buffer = new byte[1024]; var bytesRead = 0; while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { stream.Write(buffer, 0, bytesRead); //stream.Flush(); // TODO call progress changed event handler (calculate progress over all files) => use flush to have correct behaviour // TODO add progress for download } } finally { if (file.CloseStream) fileStream.Dispose(); } } boundarybytes = request.Encoding.GetBytes("\r\n--" + boundary + "--\r\n"); stream.Write(boundarybytes, 0, boundarybytes.Length); }
/// <summary> /// Performs a HTTP POST request. /// </summary> /// <param name="request">The <see cref="HttpPostRequest"/>. </param> /// <returns>The <see cref="HttpResponse"/>. </returns> public static Task <HttpResponse> PostAsync(HttpPostRequest request) { return(PostAsync(request, CancellationToken.None)); }
public static HttpResponse Post(HttpPostRequest req, Action<HttpResponse> action, Dispatcher dispatcher) { return Post(req, r => dispatcher.BeginInvoke(() => action(r))); }
/// <summary> /// Performs a HTTP POST request. /// </summary> /// <param name="request">The <see cref="HttpPostRequest"/>. </param> /// <param name="token">The <see cref="CancellationToken"/>. </param> /// <param name="progress">The <see cref="IProgress{T}"/>. </param> /// <returns>The <see cref="HttpResponse"/>. </returns> public static async Task <HttpResponse> PostAsync(HttpPostRequest request, CancellationToken token, IProgress <HttpProgress> progress = null) { var uri = GetQueryString(request, request.Query); var handler = CreateHandler(request, uri); using (var client = CreateClient(request, handler)) { var result = new HttpResponse(request); result.HttpClient = client; lock (PendingRequests) PendingRequests.Add(result); try { HttpContent content = null; if (request.RawData != null) { content = new ByteArrayContent(request.RawData); } else if (request.Files == null || request.Files.Count == 0) { content = new ByteArrayContent(request.Encoding.GetBytes(GetQueryString(request.Data))); } else { var multipartContent = new MultipartFormDataContent(); foreach (var pair in request.Data) { multipartContent.Add(new ByteArrayContent(request.Encoding.GetBytes(pair.Value)), pair.Key); } foreach (var file in request.Files) { try { var byteContent = new ByteArrayContent(await file.Stream.ReadToEndAsync(0, token, null)); byteContent.Headers.ContentType = new MediaTypeHeaderValue( file.ContentType ?? "application/octet-stream"); multipartContent.Add(byteContent, file.Name, file.Filename); } finally { if (file.CloseStream) { file.Stream.Dispose(); } } } content = multipartContent; } var response = await client.PostAsync(uri, content, token); await CreateResponse(result, uri, request, handler, response, token, progress); result.HttpStatusCode = response.StatusCode; if (!response.IsSuccessStatusCode) { result.Exception = new HttpStatusException(response.StatusCode.ToString()) { Result = result, HttpStatusCode = result.HttpStatusCode } } ; } catch (Exception ex) { if (result.Exception == null) { result.Exception = ex; throw; } } finally { lock (PendingRequests) PendingRequests.Remove(result); } if (result.Exception != null) { throw result.Exception; } return(result); } }
public static HttpResponse Post(HttpPostRequest req, Action <HttpResponse> action, Dispatcher dispatcher) { return(Post(req, r => dispatcher.BeginInvoke(() => action(r)))); }
public static Task<HttpResponse> Post(HttpPostRequest request, CancellationToken token, Action<HttpResponse> completed) { var task = PostAsync(request, token); task.ContinueWith(t => { if (t.Exception != null) completed(new HttpResponse(request) { Exception = t.Exception.InnerException }); else if (t.IsCanceled) completed(new HttpResponse(request) { Canceled = true }); else completed(t.Result); }, token); return task; }
public static HttpResponse Delete(HttpPostRequest req, Action<HttpResponse> action) { return Post(req, action, "DELETE"); }