【问题标题】:C# API Call doesn't work with HttpWebRequest but do work with PostmanC# API 调用不能与 HttpWebRequest 一起使用,但可以与 Postman 一起使用
【发布时间】:2018-03-06 16:24:28
【问题描述】:

我有以下邮递员请求:

这会按预期返回一个 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 个错误。我错过了什么?

【问题讨论】:

  • 您使用了很多在这里并不理想的方法。大多数时候你想使用 HttpClient 来发出 Restful 请求。另外,尝试使用JsonConvert.SerializeObject(),它通常是我使用的以及大多数代码示例使用的。
  • isAttachment 拼写错误。我会运行 Fiddler,并比较好请求和坏请求的负载
  • @maccettura 我愿意接受建议,你会怎么做?
  • @maccettura 我的错,我从我的评论中删除了。
  • 如果您对使用 RestSharp 感兴趣,您可以让 Postman 通过单击“代码”链接并从下拉列表中选择 C# (RestSharp) 为您生成该 c# 代码。

标签: c# json post httpwebrequest webrequest


【解决方案1】:

Postman 可以生成各种各样的代码。要将 RestSharp 与 C# 一起使用,请单击代码按钮/链接并从下拉列表中选择 C# (RestSharp)

它应该类似于:

总有一天我会为 HttpClient 和 HttpWebRequest 贡献一个生成器

【讨论】:

    【解决方案2】:

    我猜这个问题可能是由于您正在调用一个外部 url,在某些情况下它们可能会阻止像这样的抓取请求。尝试为请求设置一个用户代理来模拟浏览器调用。

    【讨论】:

    • 我添加了 ` httpWebRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36";` 但我仍然有同样的问题。为什么它会在邮递员中工作?
    • 邮递员总是设置像用户代理这样的标题,类似于浏览器调用。还可以尝试使用 fiddler 来接听邮递员的电话。
    • @J4N 刚刚在标题中添加了用户代理并为我工作谢谢。
    猜你喜欢
    • 1970-01-01
    • 2014-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-14
    • 2012-07-14
    • 1970-01-01
    相关资源
    最近更新 更多