为WebClient设置自定义标头
本文关键字:自定义 设置 WebClient | 更新日期: 2023-09-27 18:20:19
我有一个Web客户端,我想与多个供应商连接。
除了uri和数据之外,还需要考虑标头,因为不同供应商的标头可能不同。在客户端周围,我有很多其他东西——所以我想写一次这段代码。
因此,我正在尝试创建一个具有所有主要功能的基本方法,比如下面的例子,这将允许我填补调用函数的空白。
public string Post()
{
try
{
var client = new CustomWebClient();
return client.UploadString("", "");
}
catch (WebException ex)
{
switch (ex.Status)
{
case WebExceptionStatus.Timeout:
break;
default:
break;
}
throw new Exception();
}
catch (Exception ex)
{
throw new Exception();
}
finally
{
client.Dispose();
}
}
显然,将地址和数据作为参数传递是很容易的,但我如何使用client.Headers.Add()
或其他东西来设置头呢?
我正在努力想出一种既有效又不难闻的模式。
由于方法Post()是CustomWebClient的公共方法,因此通过属性设置器或构造函数初始化设置方法Post的所有必需属性将是一个很好的设计。
public class CustomWebClient
{
public NameValueCollection Headers
{
get;
set;
}
public CustomWebClient()
{
this.Headers = new NameValueCollection();
}
//Overload the constructor based on your requirement.
public string Post()
{
//Perform the post or UploadString with custom logic
}
//Overload the method Post for passing various parameters like the Url(if required)
}
在使用CustomWebClient的地方,
using (CustomWebClient client = new CustomWebClient())
{
client.Headers.Add("HeaderName","Value");
client.Post();
}
如果可能的标头数量有限,您可以在CustomWebClient
类中将它们声明为public enum
,并创建constructor
或UploadString()
函数(无论您喜欢哪一个)的重载,并将enum
的值传递给它以相应地设置标头。示例:
public class CustomWebClient {
public enum Headers { StandardForm, Json, Xml }
public CustomWebClient() {
}
//This is your original UploadString.
public string UploadString(string x, string y) {
//Call the overload with default header.
UploadString("...", "...", Headers.StandardForm);
}
//This is the overloaded UploadString.
public string UploadString(string x, string y, Headers header) {
switch(header){
case Headers.StandardForm:
client.Headers.Add("Content-Type","application/x-www-form-urlencoded");
break;
case Headers.Json:
client.Headers.Add("Content-Type","text/json");
break;
case Headers.Xml:
client.Headers.Add("Content-Type","text/xml");
break;
}
//Continue your code.
}
}
使用enum
最吸引人的好处是消除了可能的拼写错误,并给你带来了智能感,这样你就不需要记住你的选择了。