Skip to content

Instantly share code, notes, and snippets.

@justintoth
Created April 16, 2013 19:15
Show Gist options
  • Save justintoth/5398735 to your computer and use it in GitHub Desktop.
Save justintoth/5398735 to your computer and use it in GitHub Desktop.
Web Request Helper
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