How to make an HTTP POST web request

后端 未结 14 3261
有刺的猬
有刺的猬 2020-11-21 04:31

Canonical
How can I make an HTTP request and send some data using the POST method?

14条回答
  •  不要未来只要你来
    2020-11-21 04:51

    There are some really good answers on here. Let me post a different way to set your headers with the WebClient(). I will also show you how to set an API key.

            var client = new WebClient();
            string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(userName + ":" + passWord));
            client.Headers[HttpRequestHeader.Authorization] = $"Basic {credentials}";
            //If you have your data stored in an object serialize it into json to pass to the webclient with Newtonsoft's JsonConvert
            var encodedJson = JsonConvert.SerializeObject(newAccount);
    
            client.Headers.Add($"x-api-key:{ApiKey}");
            client.Headers.Add("Content-Type:application/json");
            try
            {
                var response = client.UploadString($"{apiurl}", encodedJson);
                //if you have a model to deserialize the json into Newtonsoft will help bind the data to the model, this is an extremely useful trick for GET calls when you have a lot of data, you can strongly type a model and dump it into an instance of that class.
                Response response1 = JsonConvert.DeserializeObject(response);
    

提交回复
热议问题