POST和GET Lib问题

时间:2012-01-09 12:34:56

标签: c# httpwebrequest

我正在编写一个.dll来执行Gets and Posts。 为了做到这一点,我创建了这个类:

public class BDCWebRequests
{
    // private attributes
    private static CookieContainer m_CookieJar;
    private static HttpWebRequest  m_HttpWebRequest;
    private static string          m_defaultUserAgent      = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.107 Safari/535.1";
    private static string          m_defaultContentType    = "application/x-www-form-urlencoded";

    // Public Properties
    public HttpWebRequest InternalWebRequest
    {
        get { return m_HttpWebRequest; }
    }

    /// <summary>
    /// Class Constructor
    /// </summary>
    public BDCWebRequests()
    {
        m_CookieJar = new CookieContainer();
    }

   // Methods Come Here...
}

我想要实现的是这个lib的用户使用“InternalWebRequest”属性正确配置请求的方法。

用法如下:

BDCWebRequests myInstance = new BDCWebRequests();
myInstance.InternalWebRequest.Referer = "refererUrl";
myInstance.AllowAutoRedirect          = true;
myInstance.Host                       = "hostUrl";

这样做之后,有Posts and Get Methods(这里是GET作为例子)

 public string Get(string url)
    {
        try
        {
            // Creating instance of HttpWebRequest based on URL received
            m_HttpWebRequest = (HttpWebRequest) WebRequest.Create (url);

            m_HttpWebRequest.Method                        = "GET";
            m_HttpWebRequest.UserAgent                     = m_defaultUserAgent;

            // Execute web request and wait for response
            using (HttpWebResponse resp = (HttpWebResponse) m_HttpWebRequest.GetResponse())
            {
              return new StreamReader(resp.GetResponseStream()).ReadToEnd();
            }

        }
        catch (Exception ex)
        {
            LogWriter.Error(ex);
        }

        return String.Empty;
    } 

用法:

myInstance.Get("UrlForTheRequest");

主要问题: 当用户执行GET或POST时,我遇到问题,之后,他尝试使用公共属性更改HttpWebRequest的内部实例的任何属性。

例如,如果用户调用GET,之后他会尝试:

例如,

myInstance.InternalWebRequest.Host = ""会抛出错误: "this property cannot be set after writing has started"

如何以逻辑方式实现它以便用户可以:

1 - 随时随地配置请求,而不会出现此错误 2 - 使用先前配置的请求执行获取和发布?

对不起那个长问题,请提前感谢您的耐心等待。 请不要TL:DR:)

1 个答案:

答案 0 :(得分:1)

简单:您发送请求的那一刻,从响应中读取所有必需的数据,然后创建一个新请求,并将旧请求中的所有相关参数复制到它。