Created
April 16, 2013 19:15
-
-
Save justintoth/5398735 to your computer and use it in GitHub Desktop.
Web Request Helper
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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Net; | |
using System.Configuration; | |
using System.IO; | |
namespace Housters.Business.Utility.Helpers { | |
public static class WebRequestHelper { | |
private static string APIKey = Convert.ToString(ConfigurationManager.AppSettings["BalancedAPIKey"]); | |
private static string Credentials = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(APIKey + ":")); | |
private static string ContentType = "application/json"; | |
public static string PostWithAuth(string url, string requestBody = null, string method = "POST") { | |
using (var client = new WebClient()) { | |
client.Headers.Add(HttpRequestHeader.Authorization, Credentials); | |
client.Headers.Add(HttpRequestHeader.Accept, ContentType); | |
client.Headers.Add(HttpRequestHeader.ContentType, ContentType); | |
return client.UploadString(url, method, !String.IsNullOrEmpty(requestBody) ? requestBody : "{}"); | |
} | |
} | |
public static string GetWithAuth(string url) { | |
using (var client = new WebClient()) { | |
client.Headers.Add(HttpRequestHeader.Authorization, Credentials); | |
client.Headers.Add(HttpRequestHeader.Accept, ContentType); | |
client.Headers.Add(HttpRequestHeader.ContentType, ContentType); | |
return client.DownloadString(url); | |
} | |
} | |
public static string DeleteWithAuth(string url) { | |
var request = WebRequest.Create(url); | |
request.Headers["Authorization"] = Credentials; | |
request.Headers["ContentType"] = ContentType; | |
request.Method = "DELETE"; | |
var response = (HttpWebResponse)request.GetResponse(); | |
return new StreamReader(response.GetResponseStream()).ReadToEnd(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment