使用C#发送REST请求

时间:2016-02-27 21:08:32

标签: c# json curl

我需要使用标题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();

            }
        }
    }

1 个答案:

答案 0 :(得分:0)

尝试替换

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

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