错误405,C#中的HTTPRequest上不允许使用该方法

时间:2018-10-02 19:40:56

标签: c# http curl

我正在尝试使用megaupload api通过C#获取文件信息。 我正在执行asynchronously,甚至请求也应该非常快。 根据他们在其网站上的指示,在curl上的请求应如下所示:curl https://megaupload.nz/api/v2/file/u1C0ebc4b0/info 我不知道这是否是我对整个事情的理解都不对,但是我从error那里得到Method Not Allowed的话EnsureSuccessStatusCode

这是我的代码:

static void Main(string[] args)
        {
            //var urlApiFormat = https://megaupload.nz/api/v2/file/{id}/info
            //var myURL = https://megaupload.nz/L8ydu8i3b6/Mystic_v1.1_rar
            Task.Run(() =>
            {
                var sReturn = megauploadSharpAsync(@"https://megaupload.nz/api/v2/file/L8ydu8i3b6/info");
                Console.WriteLine("Result: " + sReturn.Result);
            });

            Console.ReadKey();
        }

public static async Task<string> megauploadSharpAsync(string url)//, string outputFile)
        {
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    var postParams = new Dictionary<string, string>();

                    postParams.Add("method", "GET");
                    //postParams.Add("api_key", "keyforaccountupload");

                    using (var postContent = new FormUrlEncodedContent(postParams))
                    using (HttpResponseMessage response = await client.PostAsync(url, postContent))
                    {
                        response.EnsureSuccessStatusCode(); // Throw if httpcode is an error
                        using (HttpContent content = response.Content)
                        {
                            string result = await content.ReadAsStringAsync();
                            return result;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                await Task.Run(() =>
                {
                    //some magic
                    Console.WriteLine("Error: " + ex.Message);
                });
                return string.Empty;
            }
        }

1 个答案:

答案 0 :(得分:1)

看这行:

using (HttpResponseMessage response = await client.PostAsync(url, postContent))

PostAsync向服务器发送POST请求,而您应该发送GET请求。将PostAsync替换为GetAsync,并删除多余的postParams