c# - POST 和 GET 库问题

标签 c# httpwebrequest

我正在编写一个 .dll 来执行 Gets 和 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...
}

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

用法是这样的:

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

这样做之后,有Posts和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 时遇到问题,在此之后,他尝试使用公共(public)属性更改 HttpWebRequest 的内部实例的任何属性。

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

myInstance.InternalWebRequest.Host = "",例如,它抛出一个错误: “写入开始后无法设置此属性”

关于如何从逻辑上实现它的任何想法,以便用户可以:

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

很抱歉问了这么长的问题,在此先感谢您的耐心等待。 请不要 TL:DR :)

最佳答案

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

关于c# - POST 和 GET 库问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8788517/

相关文章:

c# - 当GenerateIfNotExistsCondition用于目标时,为什么StartCopyAsync()会抛出409冲突?

c#发送带有特殊字符的请求会干扰字符串

javascript - 如何使用javascript检查网站的响应时间?

PHP:http_get 是如何工作的?

c# - Regex 词边界表达式

c# - 为 RadGridViewComboBox 列创建数据模板

c# - 将日期时间从excel格式转换成sql格式

c# - 如何在 dll 项目中用 C++ 创建命名空间和构造函数?

C# 使用 SOAP 将对象发送到 webservice

c# - 如何在 HTTPWebRequest 期间阻止 Internet Explorer 安全警报