c# - 使用 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);
}
非常感谢您!
解决方案
解决方案:我只是在 JSON-Body 的代码中忘记了逗号。
推荐阅读
- python - 为什么即使我有日志文件,Tensorboard 也不显示任何图表?
- swift4 - /src:错误:找不到目标的源文件:MyKituraAppTests;使用 Swift 4 清单中的“路径”属性设置自定义目标路径
- python - Cython 多线程程序崩溃
- javascript - 如何自动随机化 46 个名称以在 Google 工作表中创建 46 x 6 唯一行和列?
- html - 我的 Github 页面不会将自定义 css 文件应用到网站
- c - clang:链接器命令失败,退出代码为 1
- c# - c#剃须刀,如何使用html按钮运行方法?
- r - 你能解释一下替换函数是如何计算向量长度的吗?
- php - 如何在 php 中使用路径信息?
- firebase - 带有 Cloud SQL 的 Cloud Functions - 类型上不存在属性“socketPath”