代码之家  ›  专栏  ›  技术社区  ›  J4N

C#API调用不适用于HttpWebRequest,但适用于Postman

  •  1
  • J4N  · 技术社区  · 6 年前

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

    按预期返回URL: 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 回复  |  直到 6 年前
        1
  •  3
  •   Crowcoder    6 年前

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

    它应该类似于:

    enter image description here

    有一天,我将为HttpClient和HttpWebRequest提供一个生成器

        2
  •  0
  •   Liju L    6 年前

    我想问题可能是因为您调用的是外部url,在某些情况下,它们可能会阻止这样的爬网请求。尝试将请求的useragent设置为模拟浏览器调用。