首页 > 解决方案 > 使用 C# 和 HttpWebRequest 向端点发送 POST 请求

问题描述

使用以下代码(当然使用 GET 方法)向端点发送 GET 请求对我来说没有问题,但我无法执行 POST 请求。有人可以解释一下,我必须做什么才能发布示例性 JSON-Body 吗?

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Globalization;
using System.Net;
using System.Threading;
using System.IO;
using System.Text;


namespace RestTesting

{
    class Program
    {
        static void Main(string[] args)
        {

            string url;
            url = "https://server.APIEndpoint/REST/";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/json";
            request.Accept = "application/json";
            request.KeepAlive = true;

            request.Credentials = CredentialCache.DefaultCredentials;

            Console.WriteLine("Request: {0} \"{1}\" ...", request.Method, request.RequestUri);
            Console.WriteLine(request.Headers);
            Console.WriteLine(request.ContentLength);

            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                Console.WriteLine(String.Format("Response: HTTP/{0} {1} ({1:d})\n", response.ProtocolVersion, response.StatusCode));

                Console.WriteLine(response.Headers);
                string responseText;

                using (var reader = new System.IO.StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8))
                {
                    responseText = reader.ReadToEnd();
                }

                Console.WriteLine(response.ContentType);

                if (response.ContentType.StartsWith("application/json"))
                {
                    JObject json = (JObject)JObject.Parse(responseText);
                    Console.WriteLine(json.ToString());
                }

            }
            catch (Exception err)
            {
                Console.WriteLine(err);
            }

            Console.WriteLine("Press enter to close...");
            Console.ReadLine();

        }
    }
}

这是一个 JSON 正文:

{
"reference": "Test", 
"info": "additionalInfo", 
"ID": null, 
"confidential": false,
}

问题是:System.Net.WebException:远程服务器返回错误:(404)未找到。在 System.Net.HttpWebRequest.GetResponse() 在 RestTesting.Program.Main(String[] args)

当我尝试像下面那样发布 JSON-Body 时会发生该错误(在 WebRequest.Create 方法之后):

using (var streamWriter = new StreamWriter(request.GetRequestStream()))
    {
        string data = @"{
        "reference": "Test", 
        "info": "additionalInfo", 
        "ID": null, 
        "confidential": false,  
    }";
    streamWriter.Write(data);
}

非常感谢您!

标签: c#jsonrestpost

解决方案


解决方案:我只是在 JSON-Body 的代码中忘记了逗号。


推荐阅读