Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a body for WebClient when making a Post Request

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.

like image 644
Ivan S Avatar asked Apr 19 '16 16:04

Ivan S


1 Answers

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

like image 64
Glauco Cucchiar Avatar answered Nov 15 '22 20:11

Glauco Cucchiar