简体   繁体   English

.NETCore HttpWebRequest-旧方法不起作用

[英].NETCore HttpWebRequest - Old Way isn't Working

Before I upgraded to the newest .NetCore I was able to run the HttpWebRequest, add the headers and content Type and pull the stream of the JSON file from Twitch. 在升级到最新的.NetCore之前,我能够运行HttpWebRequest,添加标头和内容类型,然后从Twitch中提取JSON文件流。 Since the upgrade this is not working. 由于升级,因此无法正常工作。 I receive a Web Exception each time I go to get the response Stream. 每当我去获取响应流时,我都会收到一个Web异常。 Nothing has changed with twitch because it still works with the old Bot. 抽搐没有改变,因为它仍然可以与旧的Bot一起使用。 The old code is below: 旧代码如下:

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))
                    {

                    }
            }
        }

I have done some research and found that I may need to start using either an HttpClient or HttpRequestMessage. 我进行了一些研究,发现我可能需要开始使用HttpClient或HttpRequestMessage。 I have tried going about this but when adding headers content type the program halts and exits. 我已经尝试过了,但是在添加标题内容时,程序会暂停并退出。 after the first line here: (when using HttpsRequestMessage) 在第一行之后:(使用HttpsRequestMessage时)

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

You are trying to add a ContentType header, but what you really want is to add an Accept header (your request is a GET and ContentType is used only on requests which contain a body, eg POST or PUT ). 您正在尝试添加ContentType标头,但您真正想要的是添加Accept标头(您的请求是GET并且ContentType仅用于包含正文的请求,例如POSTPUT )。

In .NET Core you need to use HttpClient , but remember that to correctly use it you need to leverage the use of async and await . 在.NET Core中,您需要使用HttpClient ,但是请记住要正确使用它,您需要利用asyncawait的使用。

Here it is an example: 这是一个例子:

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
        }
    }    
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM