最近在重写之前写的C#程序,正好重新整理了下这个Http工具类。很多时候我们需要在网站上进行身份认证,最常用的就是Cookie或者Session,但是各编程语言对这一特性支持程度不同,C#里的WebClient其实是可以保存登录信息的,代码如下:

!!!csharp
public class Http
{
    protected static string Session;

    public const int HttpPost = 1;
    public const int HttpGet = 2;

    /// <summary>
    /// 用于请求指定的Url,支持Post和Get方式
    /// </summary>
    /// <param name="url">请求的Url</param>
    /// <param name="param">参数</param>
    /// <param name="method">请求方式</param>
    /// <returns>页面内容</returns>
    public static string Request (string url, Dictionary<string, string> param, int method)
    {
        var wc = new WebClient();
        if (!Session.Equals(""))
            wc.Headers.Add("Cookie", Session);
        var paramStr = "";
        foreach (var pair in param)
        {
            if (!paramStr.Equals(""))
                paramStr += "&";
            paramStr += pair.Key + "=" + pair.Value;
        }
        string content;
        switch (method)
        {
            case HttpPost:
                var paramByte = Encoding.UTF8.GetBytes(paramStr);
                wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                content = Encoding.UTF8.GetString(wc.UploadData(url, "POST", paramByte));
                break;
            case HttpGet:
                wc.Encoding = Encoding.UTF8;
                content = wc.DownloadString(url + "?" + paramStr);
                break;
            default:
                return null;
        }
        if (Session.Equals(""))
            Session = wc.ResponseHeaders["Set-Cookie"].Split(';')[0];
        return content;
    }
}

注意:这里我没有对异常做处理,请在调用时或适当时处理。