[英]C# API Call doesn't work with HttpWebRequest but do work with Postman
I've the following postman request: 我有以下邮递员要求:
Which returns me as expected an URL: 这会使我返回预期的URL:
I'm trying to mimic this operation with a .Net Core 2.0 application, with the following code: 我试图用.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();
}
}
But I receive 500 errors. 但是我收到了500个错误。 What did I miss? 我错过了什么?
Postman can generate a wide variety of code. 邮差可以生成各种各样的代码。 To use RestSharp with C# click the code button/link and choose C# (RestSharp)
from the dropdown. 要在C#中使用RestSharp,请单击代码按钮/链接,然后从下拉列表中选择C# (RestSharp)
。
It should resemble: 它应该类似于:
Someday I will contribute a generator for HttpClient and HttpWebRequest 总有一天我会为HttpClient和HttpWebRequest贡献一个生成器
I guess the problem might be due to the fact that you are calling a external url there might be cases where they block crawling requests like these. 我想这个问题可能是因为您正在调用外部URL,可能会出现阻止这些爬行请求的情况。 Try setting a useragent for the request to mimic a browser call. 尝试为请求设置useragent以模仿浏览器调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.