Cookie access within a HTTP Class

Posted by James Jeffery on Programmers See other posts from Programmers or by James Jeffery
Published on 2013-07-22T00:24:47Z Indexed on 2013/10/18 16:12 UTC
Read the original article Hit count: 236

Filed under:
|

I have a HTTP class that has a Get, and Post, method. It's a simple class I created to encapsulate Post and Get requests so I don't have to repeat the get/post code throughout the application.

In C#:

class HTTP
{
    private CookieContainer cookieJar;
    private String userAgent = "...";

    public HTTP()
    {
        this.cookieJar = new CookieContainer();
    }

    public String get(String url)
    {
        // Make get request. Return the JSON
    }

    public String post(String url, String postData)
    {
        // Make post request. Return the JSON
    }
}

I've made the CookieJar a property because I want to preserve the cookie values throughout the session. If the user is logged into Twitter with my application, each request I make (be it get or post) I want to use the cookies so they remain logged in.

That's the basics of it anyway. But, I don't want to return a string in all instances. Sometimes I may want the cookie, or a header value, or something else from the request.

Ideally I'd like to be able to do this in my code:

Cookie cookie = http.get("http://google.com").cookie("g_user");
String g_user = cookie.value;

or

String source = http.get("http://google.com").body;

My question - To do this, would I need to have a Get class, and a Post class, that are included within the HTTP class and are accessible via accessors?

Within the Get and Post class I would then have the Cookie method, and the body property, and whatever else is needed.
Should I also use an interface, or create a Request class and have Post and Get extend it so that common methods and properties are available to both classes?

Or, am I thinking totally wrong?

© Programmers or respective owner

Related posts about c#

Related posts about object-oriented