0

我正在尝试从 discord webhook 下载字符串:(“ https://discordapp.com/api/webhooks/704770710509453432/GdR4absQHKDKjUiNMpw3aIpX2tx-9Z7nmPE2Sn3TUkQDM12zUczaV-m80orh7WGVzvGK ”)

当我通常使用浏览器字符串打开站点时:{“message”:“Unknown Webhook”,“code”:10015}

但是当我使用 WebClient 执行此操作时:

           WebClient wc = new WebClient();
           string site = "https://discordapp.com/api/webhooks/704770710509453432/GdR4absQHKDKjUiNMpw3aIpX2tx-9Z7nmPE2Sn3TUkQDM12zUczaV-m80orh7WGVzvGK";
           string x = wc.DownloadString(site);

它给出了“404错误”。有没有办法用 c# 获取 {"message": "Unknown Webhook", "code": 10015} 字符串?

4

1 回答 1

0

粗略的猜测是它与接受标头有关。检查 api 的文档,但我的浏览器随请求发送了额外的 17 个标头。


简单的答案是,使用HttpClient. 建议用于新开发,并在此处给出正确的响应:

using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace discordapi_headers
{
    class Program
    {
        static async Task Main(string[] args)
        {
            var client = new HttpClient();
            var response = await client.GetAsync("https://discordapp.com/api/webhooks/704770710509453432/GdR4absQHKDKjUiNMpw3aIpX2tx-9Z7nmPE2Sn3TUkQDM12zUczaV-m80orh7WGVzvGK");
            Console.WriteLine(await response.Content.ReadAsStringAsync());
        }
    }
}

但是,如果您不能,那也无济于事。我现在也很感兴趣...


哈!我应该听我自己的建议。对于 Web 服务相关的东西,你不能打败 fiddler 和 postman。事实证明,api 正在向具有 json 内容的浏览器返回自定义 404。

不幸的是,DownloadString 看到 404 并抛出 WebException。

这是使用 HttpClient 和 WebClient 的更新版本。

using System;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace discordapi_headers
{
    class Program
    {
        static readonly string url = "https://discordapp.com/api/webhooks/704770710509453432/GdR4absQHKDKjUiNMpw3aIpX2tx-9Z7nmPE2Sn3TUkQDM12zUczaV-m80orh7WGVzvGK";

        static async Task Main(string[] args)
        {
            Console.WriteLine(await UseHttpClient(url));
            Console.WriteLine(await UseWebClient(url));
        }

        private static async Task<string> UseHttpClient(string url)
        {
            var client = new HttpClient();
            var response = await client.GetAsync(url);
            return await response.Content.ReadAsStringAsync();
        }

        private static async Task<string> UseWebClient(string url)
        {
            var client = new WebClient();
            try
            {
                var response = await client.DownloadStringTaskAsync(url);
                return response;
            }
            catch (WebException wex)
            {
                using (var s = wex.Response.GetResponseStream())
                {
                    var buffer = new byte[wex.Response.ContentLength];
                    var contentBytes = await s.ReadAsync(buffer, 0, buffer.Length);
                    var content = Encoding.UTF8.GetString(buffer);
                    return content;
                }
            }
        }
    }
}
于 2020-05-31T11:37:49.917 回答