C#API调用不适用于HttpWebRequest,但可以与Postman一起使用

时间:2018-03-06 16:24:29

标签: c# json post httpwebrequest webrequest

我有以下邮递员要求: enter image description here enter image description here

它会按预期返回一个网址: enter image description here

我正在尝试使用.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个错误。我错过了什么?

2 个答案:

答案 0 :(得分:2)

邮递员可以生成各种各样的代码。要在C#中使用RestSharp,请单击代码按钮/链接,然后从下拉列表中选择C# (RestSharp)

它应该类似于:

enter image description here

总有一天我会为HttpClient和HttpWebRequest提供一个生成器

答案 1 :(得分:0)

我想这个问题可能是因为您正在调用外部网址,可能会出现阻止抓取请求的情况。尝试为请求设置一个useragent来模仿浏览器调用。