.NETCore HttpWebRequest - 旧方法不起作用

Zac*_*ett 1 c# json httpwebrequest twitch .net-core

在升级到最新的 .NetCore 之前,我能够运行 HttpWebRequest,添加标头和内容类型,并从 Twitch 拉取 JSON 文件的流。由于升级这不起作用。每次我去获取响应流时,我都会收到一个 Web 异常。twitch 没有任何改变,因为它仍然适用于旧的 Bot。旧代码如下:

private const string Url = "https://api.twitch.tv/kraken/streams/channelname";
HttpWebRequest request;
        try
        {
            request = (HttpWebRequest)WebRequest.Create(Url);
        }

        request.Method = "Get";
        request.Timeout = 12000;
        request.ContentType = "application/vnd.twitchtv.v5+json";
        request.Headers.Add("Client-ID", "ID");
        try
        {
            using (var s = request.GetResponse().GetResponseStream())
            {
                if (s != null)
                    using (var sr = new StreamReader(s))
                    {

                    }
            }
        }
Run Code Online (Sandbox Code Playgroud)

我做了一些研究,发现我可能需要开始使用 HttpClient 或 HttpRequestMessage。我已经尝试解决这个问题,但是当添加标题内容类型时,程序会停止并退出。在此处的第一行之后:(使用 HttpsRequestMessage 时)

request.Content.Headers.ContentType.MediaType = "application/vnd.twitchtv.v5+json";
request.Content.Headers.Add("Client-ID", "rbp1au0xk85ej6wac9b8s1a1amlsi5");
Run Code Online (Sandbox Code Playgroud)

Fed*_*uma 5

您正在尝试添加ContentType标头,但您真正想要的是添加Accept标头(您的请求是 aGET并且ContentType仅用于包含正文的请求,例如POSTor PUT)。

在.NET的核心,你需要使用HttpClient,但请记住,正确地使用它,你需要利用使用async和await。

这是一个例子:

using System.Net.Http;
using System.Net.Http.Headers;

private const string Url = "https://api.twitch.tv/kraken/streams/channelname";

public static async Task<string> GetResponseFromTwitch()
{
    using(var client = new HttpClient())
    {
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.twitchtv.v5+json"));
        client.DefaultRequestHeaders.Add("Client-ID", "MyId");

        using(var response = await client.GetAsync(Url))
        {
            response.EnsureSuccessStatusCode();

            return await response.Content.ReadAsStringAsync(); // here we return the json response, you may parse it
        }
    }    
}
Run Code Online (Sandbox Code Playgroud)