【问题标题】:Post data to A URL by C#通过 C# 将数据发布到 A URL
【发布时间】:2023-01-01 02:44:59
【问题描述】:

我如何将以下信息发布到本网站“http://restapi.adequateshop.com/api/Tourist” 通过 C# 代码?

tourist_name:“虚拟” tourist_email: "test123@test.com" tourist_location:“巴黎”

static void Main(string[] args)
        {
            //create the constructor with post type and few data
            string data = "tourist_name=Mike&tourist_email=miked123@gmail.com&tourist_location=Paris";
            MyWebRequest myRequest = new MyWebRequest("http://restapi.adequateshop.com/api/Tourist", "POST", data);
            //show the response string on the console screen.
            string Response = myRequest.GetResponse();
        }

【问题讨论】:

    标签: json wcf post request get


    【解决方案1】:

    您可以将数据放在一个新类中:

    class RequestData
    {
      string tourist_name { get; set; }
      string tourist_email { get; set; }
      string tourist_location { get; set; }
    }
    

    然后你可以将你的对象序列化为 JSON:

    RequestData requestData = new RequestData();
    requestData.tourist_name ="Mike";
    requestData.tourist_email ="miked123@gmail.com";
    requestData.tourist_location ="Paris";
    
    string jsonData = JsonConvert.SerializeObject(requestData);
    

    然后将您的 JSON 发送到 API

    string URL="http://restapi.adequateshop.com/api/Tourist";
    var jsonContent = new StringContent(jsonData,Encoding.UTF8,"application/json");
    var result = client.PostAsync(URL,jsonContent).Result;
    

    我希望这回答了你的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-17
      • 2012-04-30
      • 2013-02-12
      • 2013-10-17
      • 2023-03-30
      • 1970-01-01
      • 2014-09-09
      • 1970-01-01
      相关资源
      最近更新 更多