使用 C# 和 HttpWebRequest 向端点发送 POST 请求
Send a POST request to an endpoint with C# and HttpWebRequest
我可以使用以下代码向端点发送 GET 请求(当然是使用 GET 方法),但我无法执行 POST 请求。有人可以解释一下,我必须做什么才能 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-Body:
{
"reference": "Test",
"info": "additionalInfo",
"ID": null,
"confidential": false,
}
问题是:System.Net.WebException:远程服务器返回错误:(404) 未找到。在 System.Net.HttpWebRequest.GetResponse() 在 RestTesting.Program.Main(String[] args)
当我尝试 post 如下所示的 JSON-Body 时(在 WebRequest.Create 方法之后):
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string data = @"{
"reference": "Test",
"info": "additionalInfo",
"ID": null,
"confidential": false,
}";
streamWriter.Write(data);
}
非常感谢您!
解决方案:我只是在 JSON-Body 的代码中忘记了一个逗号。
我可以使用以下代码向端点发送 GET 请求(当然是使用 GET 方法),但我无法执行 POST 请求。有人可以解释一下,我必须做什么才能 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-Body:
{
"reference": "Test",
"info": "additionalInfo",
"ID": null,
"confidential": false,
}
问题是:System.Net.WebException:远程服务器返回错误:(404) 未找到。在 System.Net.HttpWebRequest.GetResponse() 在 RestTesting.Program.Main(String[] args)
当我尝试 post 如下所示的 JSON-Body 时(在 WebRequest.Create 方法之后):
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string data = @"{
"reference": "Test",
"info": "additionalInfo",
"ID": null,
"confidential": false,
}";
streamWriter.Write(data);
}
非常感谢您!
解决方案:我只是在 JSON-Body 的代码中忘记了一个逗号。