2012-12-24 69 views
3

我有如下所示的代码做一个POST到服务器:在C#WebClient中使用UploadString时,是否需要编码值?

string URI = "http://mydomain.com/foo"; 
string myParameters = 
    "&token=1234" + 
    "&text=" + HttpUtility.UrlEncode(someVariable); 

using (WebClient wc = new WebClient()) 
{ 
     wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; 
     string HtmlResult = wc.UploadString(URI, myParameters); 
} 

需要它来urlencode的参数,比如我做的还是在幕后自动做UploadString处理?我不想冒任何类型的双重编码。

回答

1

是的,如果您使用UploadString方法,则需要对它们进行编码。

但是你可以用更智能的过载为你的情况(UploadValues):

string URI = "http://mydomain.com/foo"; 
var values = new NameValueCollection 
{ 
    { "token", "1234" }, 
    { "text", someVariable }, 
}; 

using (var wc = new WebClient()) 
{ 
    byte[] result = wc.UploadValues(URI, values); 
    string htmlResult = Encoding.UTF8.GetString(result); 
} 

现在您不再需要担心任何编码。发送请求时,WebClient将考虑到它们。另外你会注意到我删除了你添加的application/x-www-form-urlencoded,因为当你使用UploadValues方法时,这个Content-Type头将自动添加到请求中。

相关问题