Take the 2-minute tour ×
Stack Apps is a question and answer site for apps, scripts, and development with the Stack Exchange API. It's 100% free, no registration required.

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;
        }
    }
}
share|improve this question
    
Thank you. I spent the whole afternoon trying to figure out what I was doing wrong. The GZIP compression line fixed everything! –  Diago Sep 7 '10 at 18:57
    
@diago - my pleasure. If you would like a full featured .net client library - check out stackapps.com/questions/386 –  Sky Sanders Sep 7 '10 at 19:12
    
Thanks. It looks good. I want to wrap my head around how the API works first before moving to using a library. –  Diago Sep 8 '10 at 8:01

You must log in to answer this question.

Browse other questions tagged .