Skip to content

Instantly share code, notes, and snippets.

@KyleGobel
Created April 27, 2014 06:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KyleGobel/11339054 to your computer and use it in GitHub Desktop.
Save KyleGobel/11339054 to your computer and use it in GitHub Desktop.
Will service stack take me?? Still missing some PCL stuff, but I don't think this can be done PCL anyway..or if it can it's alot harder and I don't know how
public static class HttpUtilExtensions
{
public static Task<string> PostJsonToUrlAsync(this string url, object data,
Action<HttpWebRequest> requestFilter = null, Action<HttpWebResponse> responseFilter = null,
Action<string> callback = null)
{
return SendStringToUrlAsync(url, method: "POST", requestBody: data.ToJson(), contentType: MimeTypes.Json, accept: MimeTypes.Json,
requestFilter: requestFilter, responseFilter: responseFilter, callback: callback);
}
public static Task<string> SendStringToUrlAsync(this string url, string method = null, string requestBody = null,
string contentType = null, string accept= "*/*", Action<HttpWebRequest> requestFilter = null,
Action<HttpWebResponse> responseFilter = null, Action<string> callback = null)
{
var webReq = (HttpWebRequest)WebRequest.Create(url);
if (method != null)
webReq.Method = method;
if (contentType != null)
webReq.ContentType = contentType;
webReq.Accept = accept;
if (requestFilter != null)
{
requestFilter(webReq);
}
if (requestBody != null)
{
using (var reqStream = webReq.GetRequestStream())
using (var writer = new StreamWriter(reqStream))
{
writer.Write(requestBody);
}
}
var taskWebRes = webReq.GetResponseAsync();
return taskWebRes.ContinueWith(task =>
{
var webResp = task.Result;
using (var stream = webResp.GetResponseStream())
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment