How do you do an HTTP Put?

前端 未结 11 2018
孤独总比滥情好
孤独总比滥情好 2020-12-04 14:19

We have this software that has a webservices component.

Now, the administrator of this system has come to me, wanting to import data into the system by using the webs

11条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-04 14:35

    Here's a C# example using HttpWebRequest:

    using System;
    using System.IO;
    using System.Net;
    
    class Test
    {
            static void Main()
            {
                    string xml = "...";
                    byte[] arr = System.Text.Encoding.UTF8.GetBytes(xml);
                    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://localhost/");
                    request.Method = "PUT";
                    request.ContentType = "text/xml";
                    request.ContentLength = arr.Length;
                    Stream dataStream = request.GetRequestStream();
                    dataStream.Write(arr, 0, arr.Length);
                    dataStream.Close();
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    string returnString = response.StatusCode.ToString();
                    Console.WriteLine(returnString);
            }
    }
    

    Update: there's now an HttpClient class in System.Net.Http (available as a NuGet package) that makes this a bit easier:

    using System;
    using System.Net.Http;
    
    class Program
    {
        static void Main()
        {
            var client = new HttpClient();
            var content = new StringContent("...");
            var response = client.PutAsync("http://localhost/", content).Result;
            Console.WriteLine(response.StatusCode);
        }
    }
    

提交回复
热议问题