如何使用C#中的WebClient将数据发布到特定URL

Sol*_*ake 305 c# post webclient

我需要使用WebClient的"HTTP Post"将一些数据发布到我拥有的特定URL.

现在,我知道这可以通过WebRequest完成,但出于某些原因我想使用WebClient.那可能吗?如果是这样,有人能告诉我一些例子还是指向正确的方向?

Sol*_*ake 365

我刚刚找到解决方案,是的,它比我想象的要容易:)

所以这是解决方案:

string URI = "http://www.myurl.com/post.php";
string myParameters = "param1=value1&param2=value2&param3=value3";

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

它像魅力:)

  • 挑剔:最好在这里使用[`HttpRequestHeader.ContentType`](http://msdn.microsoft.com/en-us/library/system.net.httprequestheader.aspx)枚举成员,例如这个`web.Headers [HttpRequestHeader .ContentType]`:p (27认同)
  • 另一个挑剔,你应该使用.dispose或"使用"成语来正确处理webclient:using(WebClient wc = new WebClient()){//这里你的代码} (11认同)
  • @ alpsystems.com IDisposable对象需要由程序员正确处理,方法是在使用中包装或通过显式调用.Dispose().垃圾收集器无法跟踪非托管资源,如文件处理程序,数据库连接等 (3认同)

End*_*ono 347

有一个名为UploadValues的内置方法可以发送HTTP POST(或任何类型的HTTP方法)并以适当的格式数据格式处理请求体的构造(用"&"连接参数和通过url编码转义字符):

using(WebClient client = new WebClient())
{
    var reqparm = new System.Collections.Specialized.NameValueCollection();
    reqparm.Add("param1", "<any> kinds & of = ? strings");
    reqparm.Add("param2", "escaping is already handled");
    byte[] responsebytes = client.UploadValues("http://localhost", "POST", reqparm);
    string responsebody = Encoding.UTF8.GetString(responsebytes);
}
Run Code Online (Sandbox Code Playgroud)

  • 这个是我的最爱.让框架为您服务! (34认同)
  • @BurakKarakuş你的意思是你想在体内发送JSON?然后你可能想使用[WebClient.UploadString](https://msdn.microsoft.com/en-us/library/d0d3595k(v = vs.110).aspx).不要忘记在标题中添加Content-Type:application/json. (6认同)

Pra*_*ana 39

使用WebClient.UploadStringWebClient.UploadData您可以轻松地将数据发布到服务器.我将使用UploadData显示一个示例,因为UploadString的使用方式与DownloadString相同.

byte[] bret = client.UploadData("http://www.website.com/post.php", "POST",
                System.Text.Encoding.ASCII.GetBytes("field1=value1&amp;field2=value2") );

            string sret = System.Text.Encoding.ASCII.GetString(bret);
Run Code Online (Sandbox Code Playgroud)

更多:http://www.daveamenta.com/2008-05/c-webclient-usage/

  • 更好地使用:client.Encoding = System.Text.UTF8Encoding.UTF8; string varValue = Uri.EscapeDataString(value); (5认同)

And*_*rew 21

string URI = "site.com/mail.php";
using (WebClient client = new WebClient())
{
    System.Collections.Specialized.NameValueCollection postData = 
        new System.Collections.Specialized.NameValueCollection()
       {
              { "to", emailTo },  
              { "subject", currentSubject },
              { "body", currentBody }
       };
    string pagesource = Encoding.UTF8.GetString(client.UploadValues(URI, postData));
}
Run Code Online (Sandbox Code Playgroud)


TeJ*_*TeJ 20

//Making a POST request using WebClient.
Function()
{    
  WebClient wc = new WebClient();

  var URI = new Uri("http://your_uri_goes_here");

  //If any encoding is needed.
  wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";
  //Or any other encoding type.

  //If any key needed

  wc.Headers["KEY"] = "Your_Key_Goes_Here";

  wc.UploadStringCompleted += 
      new UploadStringCompletedEventHandler(wc_UploadStringCompleted);

  wc.UploadStringAsync(URI,"POST","Data_To_Be_sent");    
}

void wc__UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)    
{  
  try            
  {          
     MessageBox.Show(e.Result); 
     //e.result fetches you the response against your POST request.         
  }
  catch(Exception exc)         
  {             
     MessageBox.Show(exc.ToString());            
  }
}
Run Code Online (Sandbox Code Playgroud)


Ogg*_*las 5

使用 simpleclient.UploadString(adress, content);通常工作得很好,但我认为应该记住,WebException如果没有返回 HTTP 成功状态代码,则会抛出 a 。我通常这样处理它以打印远程服务器返回的任何异常消息:

try
{
    postResult = client.UploadString(address, content);
}
catch (WebException ex)
{
    String responseFromServer = ex.Message.ToString() + " ";
    if (ex.Response != null)
    {
        using (WebResponse response = ex.Response)
        {
            Stream dataRs = response.GetResponseStream();
            using (StreamReader reader = new StreamReader(dataRs))
            {
                responseFromServer += reader.ReadToEnd();
                _log.Error("Server Response: " + responseFromServer);
            }
        }
    }
    throw;
}
Run Code Online (Sandbox Code Playgroud)