Created
April 27, 2014 06:41
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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