使用 C# 放置 REST 请求

本文关键字:请求 REST 放置 使用 | 更新日期: 2023-09-27 18:36:28

我需要用标头IDENTITY_KEY做一个PUT请求。

具体来说,我需要用 C# 执行以下操作,我现在已经用 curl 完成了:

curl --request PUT '
--header IDENTITY_KEY: c956c302086a042dd0426b4e62652273e05a6ce74d0b77f8b5602e0811025066 '
--header Content-type: application/json '
--data @data.txt http://192.168.1.200:8081/data/testApp_provider/RE0025

其中data.txt包含 JSON:

{"observations":[{
    "value":"10.1"
   },{
    "value":"11.2",
    "timestamp":"20/12/2015T12:34:45"
   },{
    "value":"12.3",
    "timestamp":"20/12/2015T10:34:45"
   }
]}

我该怎么做?

我尝试使用此代码,但它不起作用:

using System;
using System.IO;
using System.Net;
namespace ConsoleApplication6
{
    class Program
    {
        static void Main(string[] args)
        {
            var request = WebRequest.Create("http://192.168.1.200/data/testApp_provider/RE0025");
            request.Method = "PUT";
            request.ContentType = "application/json; charset=utf-8";
            request.Headers["IDENTITY_KEY"] = "c956c302086a042dd0426b4e62652273e05a6ce74d0b77f8b5602e081102506";
                using (var writer = new StreamWriter(request.GetRequestStream()))
            {
                var serializer = new JavaScriptSerializer();
                var payload = serializer.Serialize(new
                {
                    value = "97",
                    timestamp = "20 / 12 / 2015T12:34:45"
                });
                writer.Write(payload);
            }
            using (var response = request.GetResponse())
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                string result = reader.ReadToEnd();
            }
        }
    }

使用 C# 放置 REST 请求

尝试替换

request.Headers["IDENTITY_KEY"] = "c956c302086a042dd0426b4e62652273e05a6ce74d0b77f8b5602e081102506";

request.Headers.Add("IDENTITY_KEY", "c956c302086a042dd0426b4e62652273e05a6ce74d0b77f8b5602e081102506");