【问题标题】:How to send x-www-form-urlencoded in a post request in webclient? [duplicate]如何在 webclient 的 post 请求中发送 x-www-form-urlencoded? [复制]
【发布时间】:2023-03-05 19:44:01
【问题描述】:

我知道我可以发送 json,但我找不到如何发送 x-www-form-urlencoded。我不知道该尝试什么,因为我找不到任何东西。

WebClient wc = new WebClient();


string data = "channel_id=+12039273888&channel_type=phone&channel_verification=514950";

wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";

string result = wc.UploadString("http://3.86.171.88/api/login", data);

System.Console.WriteLine(result);

【问题讨论】:

    标签: c# webclient


    【解决方案1】:

    您可以在WebClient 类上使用UploadString() 方法,例如

    string data = "name=john&age=20&city=Uganda";
    using (WebClient client = new WebClient())
    {
        client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
        string result = client.UploadString(url of api resource, data);
    }
    

    【讨论】:

    • 我尝试将其添加到我的代码中,但出现 402 错误 - 无法处理的不完整。
    【解决方案2】:
            HttpClient client = new HttpClient();
    
            HttpContent content = new FormUrlEncodedContent(
                new List<KeyValuePair<string, string>>()
                );
    
            content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
            content.Headers.ContentType.CharSet = "UTF-8";
            client.DefaultRequestHeaders.ExpectContinue = false;
            HttpResponseMessage response = await client.PostAsync(new Uri(https://some url...), content);
    

    希望这会有所帮助.. 因为 HttpClient 是最新的也更好地倾向于 restapi..

    【讨论】:

      猜你喜欢
      • 2018-07-21
      • 2021-01-19
      • 1970-01-01
      • 1970-01-01
      • 2014-03-30
      • 1970-01-01
      • 2018-03-24
      • 2017-12-18
      • 1970-01-01
      相关资源
      最近更新 更多