How to send x-www-form-urlencoded in a post request in webclient? [duplicate]

荒凉一梦 提交于 2021-01-05 10:50:25

问题


I know I can send json but I couldn't find how to send x-www-form-urlencoded. I don't know what to try as I couldn't find anything.

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

回答1:


You can use UploadString() method on WebClient class like

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



回答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 resposne = await client.PostAsync(new Uri(https://some url...), content);

hope this helps.. since HttpClient is latest also lean toawrds restapi better..



来源:https://stackoverflow.com/questions/56188371/how-to-send-x-www-form-urlencoded-in-a-post-request-in-webclient

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!