用System.Net.WebClient发送请求

本文关键字:请求 WebClient System Net | 更新日期: 2023-09-27 18:06:51

我相信答案很简单,但是我发现的代码样本都不起作用…基本上我试图发送一个post请求使用System.Net。WebClient,带字符串参数;但服务器将参数获取为空。它必须在dotnet 2中编写,所以我不能使用HttpClient(顺便说一下)。

客户:

        using(var client = new WebClient())
        {
            try
            {
                var res = client.UploadString(_uri, "POST", "test");
                if (res != "test")
                    return false;
            }
            catch (Exception exception)
            {
                  Console.WriteLine(exception.Message);
                  return false;
            }
服务:

            public string Post([FromBody]string value)
            {
                return value;
            }

用System.Net.WebClient发送请求

还没有测试过这段代码,但是可以试试。您可以添加更多的标头,如果它抛出更多错误,则可能需要更具体的标头。

using (WebClient client = new WebClient())
{
string yourURL = "http://example.com/example.php";
string PARM= "par1=value1&par=value2";
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string result= client.UploadString(yourURL, PARM);
if(result != "test"){
return false
}
}