Set a body for WebClient when making a Post Request

与世无争的帅哥 提交于 2020-05-12 20:36:31

问题


So I have an api that I want to call to. The first call is an ahoy call and in the body of the request I need to send the ship_type, piratename and my piratepass. I then want to read the response which has my treasure booty that i will use for later.

I'm able to do this with web request. but i feel like there is a better way to do it with webclient.

(way I currently do it in webrequest)

        //Credentials for the Pirate api
        string piratename = "IvanTheTerrible";
        string piratepass= "YARRRRRRRR";

        string URI = "https://www.PiratesSuperSecretHQ.com/sandyShores/api/respectmyauthority";

        WebRequest wr = WebRequest.Create(URI);

        wr.Method = "POST";
        wr.ContentType = "application/x-www-form-urlencoded";

        string bodyData = "ship_type=BattleCruiser&piratename=" + piratename + "&piratepass=" + piratepass;

        ASCIIEncoding encoder = new ASCIIEncoding();

        byte[] byte1 = encoder.GetBytes(bodyData);

        wr.ContentLength = byte1.Length;
        //writes the body to the request
        Stream newStream = wr.GetRequestStream();

        newStream.Write(byte1, 0, byte1.Length);
        newStream.Close();            

        WebResponse wrep = wr.GetResponse();

        string result;

        using (var reader = new StreamReader(wrep.GetResponseStream()))
        {
            result = reader.ReadToEnd(); // do something fun...
        }

Thanks in advance either way.


回答1:


You can do with this simple code

Uri uri = new Uri("yourUri");
string data = "yourData";

WebClient client = new WebClient();
var result = client.UploadString(uri, data);

Remember that you can use UploadStringTaskAsync if you want to be async



来源:https://stackoverflow.com/questions/36723705/set-a-body-for-webclient-when-making-a-post-request

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