C# API 调用不适用于 HttpWebRequest 但可用于 Postman
C# API Call doesn't work with HttpWebRequest but do work with Postman
我有以下邮递员请求:
哪个returns我果然是URL:
我正在尝试使用 .Net Core 2.0 应用程序模拟此操作,代码如下:
static void Main(string[] args)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://epaper.20minuten.ch/index.cfm/epaper/1.0/getEditionDoc");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
var serializer = new Newtonsoft.Json.JsonSerializer();
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
using (var tw = new Newtonsoft.Json.JsonTextWriter(streamWriter))
{
serializer.Serialize(tw,
new
{
editions = new[]
{
new
{
defId = "648",
publicationDate = "2018-03-06"
}
},
isAttachment = true,
fileName = "Gesamtausgabe_Lausanne_2018-03-06.pdf"
});
}
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
Console.ReadLine();
}
}
但是我收到 500 个错误。我错过了什么?
我猜问题可能是由于您正在调用外部 url 可能会出现它们阻止像这样的抓取请求的情况。尝试为请求设置用户代理以模拟浏览器调用。
Postman 可以生成各种各样的代码。要将 RestSharp 与 C# 结合使用,请单击代码 button/link 并从下拉列表中选择 C# (RestSharp)
。
它应该类似于:
有一天我会为 HttpClient 和 HttpWebRequest 贡献一个生成器
我有以下邮递员请求:
哪个returns我果然是URL:
我正在尝试使用 .Net Core 2.0 应用程序模拟此操作,代码如下:
static void Main(string[] args)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://epaper.20minuten.ch/index.cfm/epaper/1.0/getEditionDoc");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
var serializer = new Newtonsoft.Json.JsonSerializer();
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
using (var tw = new Newtonsoft.Json.JsonTextWriter(streamWriter))
{
serializer.Serialize(tw,
new
{
editions = new[]
{
new
{
defId = "648",
publicationDate = "2018-03-06"
}
},
isAttachment = true,
fileName = "Gesamtausgabe_Lausanne_2018-03-06.pdf"
});
}
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
Console.ReadLine();
}
}
但是我收到 500 个错误。我错过了什么?
我猜问题可能是由于您正在调用外部 url 可能会出现它们阻止像这样的抓取请求的情况。尝试为请求设置用户代理以模拟浏览器调用。
Postman 可以生成各种各样的代码。要将 RestSharp 与 C# 结合使用,请单击代码 button/link 并从下拉列表中选择 C# (RestSharp)
。
它应该类似于:
有一天我会为 HttpClient 和 HttpWebRequest 贡献一个生成器