简体   繁体   中英

Using REST PUT in C#

I am working with a REST API and I am trying to do a PUT method to it. I found this code I was going to give a try:

    static void Main()
    {
            string xml = "<xml>...</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);
    }

One thing I want to do if possible, and can't seem to find anything about it. I would like to pass the data of text fields so, txtEmail.Text , txtFirstName.Text , etc. Is this possible? If, so how would I go about doing this? Does this code look like it would work? Unfortunately the API I'm working with has very very little documentation. Thanks!

The code lines

Stream dataStream = request.GetRequestStream();
dataStream.Write(arr, 0, arr.Length);
dataStream.Close();

do write something to the remote website. The request stream is the way to provide data to the server, so you would create a string / object that you write to the stream to transfer to the server. In your example <xml>...</xml> is sent to the server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM