簡體   English   中英

如何在 C# 中使用 WebClient 將數據發布到特定 URL

[英]How to post data to specific URL using WebClient in C#

我需要使用帶有 WebClient 的“HTTP Post”將一些數據發布到我擁有的特定 URL。

現在,我知道這可以通過 WebRequest 來完成,但出於某些原因,我想改用 WebClient。 那可能嗎? 如果是這樣,有人可以向我展示一些示例或指出正確的方向嗎?

我剛剛找到了解決方案,是的,它比我想象的要容易:)

所以這里是解決方案:

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);
}

它的作用就像魅力:)

有一個名為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);
}

使用WebClient.UploadStringWebClient.UploadData您可以輕松地將數據 POST 到服務器。 我將展示一個使用 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);

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

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));
}
//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());            
  }
}

使用簡單的client.UploadString(adress, content); 通常工作正常,但我認為應該記住,如果沒有返回 HTTP 成功狀態代碼,將拋出WebException 我通常像這樣處理它以打印遠程服務器返回的任何異常消息:

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;
}

使用帶有模型的 webapiclient 發送序列化 json 參數請求。

PostModel.cs

    public string Id { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public int Age { get; set; }

WebApiClient.cs

internal class WebApiClient  : IDisposable
  {

    private bool _isDispose;

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    public void Dispose(bool disposing)
    {
        if (!_isDispose)
        {

            if (disposing)
            {

            }
        }

        _isDispose = true;
    }

    private void SetHeaderParameters(WebClient client)
    {
        client.Headers.Clear();
        client.Headers.Add("Content-Type", "application/json");
        client.Encoding = Encoding.UTF8;
    }

    public async Task<T> PostJsonWithModelAsync<T>(string address, string data,)
    {
        using (var client = new WebClient())
        {
            SetHeaderParameters(client);
            string result = await client.UploadStringTaskAsync(address, data); //  method:
    //The HTTP method used to send the file to the resource. If null, the default is  POST 
            return JsonConvert.DeserializeObject<T>(result);
        }
    }
}

業務調用方法

    public async Task<ResultDTO> GetResultAsync(PostModel model)
    {
        try
        {
            using (var client = new WebApiClient())
            {
                var serializeModel= JsonConvert.SerializeObject(model);// using Newtonsoft.Json;
                var response = await client.PostJsonWithModelAsync<ResultDTO>("http://www.website.com/api/create", serializeModel);
                return response;
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }

    }

這是清晰的答案:

public String sendSMS(String phone, String token) {
    WebClient webClient = WebClient.create(smsServiceUrl);

    SMSRequest smsRequest = new SMSRequest();
    smsRequest.setMessage(token);
    smsRequest.setPhoneNo(phone);
    smsRequest.setTokenId(smsServiceTokenId);

    Mono<String> response = webClient.post()
          .uri(smsServiceEndpoint)
          .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
          .body(Mono.just(smsRequest), SMSRequest.class)
          .retrieve().bodyToMono(String.class);

    String deliveryResponse = response.block();
    if (deliveryResponse.equalsIgnoreCase("success")) {
      return deliveryResponse;
    }
    return null;
}

大多數答案都是舊的。 只是想分享對我有用的東西。 為了異步處理,即在 .NET 6.0 Preview 7 中使用 WebClient 異步將數據發布到特定 URL,.NET Core 和其他版本可以使用WebClient.UploadStringTaskAsync Method完成。

使用命名空間System.Net; 對於ResponseType類來捕獲來自服務器的響應,我們可以使用此方法將數據POST到特定的 URL。 確保在調用此方法時使用await關鍵字

    public async Task<ResponseType> MyAsyncServiceCall()
    {
        try
        {
            var uri = new Uri("http://your_uri");
            var body= "param1=value1&param2=value2&param3=value3";

            using (var wc = new WebClient())
            {
                wc.Headers[HttpRequestHeader.Authorization] = "yourKey"; // Can be Bearer token, API Key etc.....
                wc.Headers[HttpRequestHeader.ContentType] = "application/json"; // Is about the payload/content of the current request or response. Do not use it if the request doesn't have a payload/ body.
                wc.Headers[HttpRequestHeader.Accept] = "application/json"; // Tells the server the kind of response the client will accept.
                wc.Headers[HttpRequestHeader.UserAgent] = "PostmanRuntime/7.28.3"; 
                
                string result = await wc.UploadStringTaskAsync(uri, body);
                return JsonConvert.DeserializeObject<ResponseType>(result);
            }
        }
        catch (Exception e)
        {
            throw new Exception(e.Message);
        }
    }
string URI = "http://www.myurl.com/post.php";
string myParameters = "param1=value1&param2=value2&param3=value3"

可以簡化為

http://www.myurl.com/post.php?param1=value1&param2=value2&param3=value3

這總是有效的。 我發現原來的一個上下班。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM