This tip shows a simple and reliable way to create HttpWebRequest
that are configured to properly query the api.
With the exception of the AutomaticDecompression
assignment, this code can be used in Silverlight.
Example as Test
using System;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using NUnit.Framework;
namespace StackApps.Tips
{
public class SimpleRequestFactoryFixture
{
[Test]
public void Test()
{
string yourApiKey = "";
Uri methodUri = new Uri("http://api.stackapps.com/0.9/questions/unanswered");
var parameters = new NameValueCollection
{
{"sort", "votes"},
{"min", "5"},
{"order", "asc"}
};
HttpWebRequest request =
SimpleRequestFactory.Create(methodUri, parameters, yourApiKey);
Console.WriteLine(request.RequestUri.AbsoluteUri);
string json;
using (var response = request.GetResponse())
{
using (var stream = response.GetResponseStream())
{
using (var reader = new StreamReader(stream))
{
json = reader.ReadToEnd();
}
}
}
Console.WriteLine(json);
}
}
}
The Code:
using System;
using System.Collections.Specialized;
using System.Linq;
using System.Net;
using System.Web;
namespace StackApps.Tips
{
public class SimpleRequestFactory
{
// this value is a guess, have not tested yet
public const int MaxQueryStringLength = 1000;
// this value is verified
public const int MaxPathLength = 240;
private const string MaxPathErrorMessage
= "Path length exceeds maximum recommended value of {0}";
private const string MaxQueryStringErrorMessage
= "Query string length exceeds maximum recommended value of {0}";
public static HttpWebRequest Create(Uri url, NameValueCollection parameters, string apiKey)
{
string queryString = String.Join("&", parameters.AllKeys
.Select(
name =>
String.Concat(name, "=",
HttpUtility.UrlEncode(parameters[name])))
.ToArray());
var fullUrl = new Uri(String.Format("{0}?{1}{2}", url.AbsoluteUri,
string.IsNullOrEmpty(apiKey) ? "" : String.Format("key={0}&", apiKey)
, queryString));
if (fullUrl.AbsolutePath.Length > MaxPathLength)
{
throw new ArgumentException(String.Format(MaxPathErrorMessage, MaxPathLength), "url");
}
if (fullUrl.Query.Length > MaxQueryStringLength)
{
throw new ArgumentException(String.Format(MaxQueryStringErrorMessage, MaxQueryStringLength), "url");
}
var request = (HttpWebRequest)WebRequest.Create(fullUrl);
request.AutomaticDecompression = DecompressionMethods.GZip;
return request;
}
}
}