UWP C# 项目中的 HTTP 重定向请求失败

Posted

技术标签:

【中文标题】UWP C# 项目中的 HTTP 重定向请求失败【英文标题】:The HTTP redirect request failed in UWP C# project 【发布时间】:2019-10-10 12:02:07 【问题描述】:

当我尝试获取此 url 的文本(整个字符串)(例如)时,我收到此错误“HTTP 重定向请求失败”:“https://apic-desktop.musixmatch.com/ws/1.1/macro.subtitles.get?format=json&q_track=Mi%20Mi%20Mi%20%28Radio%20Edit%29&q_artist=SEREBRO&user_language=en&subtitle_format=mxm&app_id=web-desktop-app-v1.0&usertoken=SECRET TOKEN”但它在 chrome 中工作,我必须得到那个 json 文件https://pastebin.com/GJdLK3BA(我把它上传到 Pastebin)

平台:UWP x64 系统:Windows 10 pro 4 月更新

public string URLToString(string url)

    HttpClient client = new HttpClient();
    HttpResponseMessage response = client.GetAsync(url).Result;
    string result = null;
    if (response.IsSuccessStatusCode)
    
       result = client.GetStringAsync(url).Result;
    
    else
    
       result = null;
    
    return result;
 

LyURL = "https://apic-desktop.musixmatch.com/ws/1.1/matcher.lyrics.get?format=json&q_track=" + Uri.EscapeUriString(Title.Text) + "&q_artist=" + Uri.EscapeUriString(Arti.Text) + "&user_language=en&subtitle_format=mxm&app_id=web-desktop-app- v1.0&usertoken=*SECRET TOKEN*";

JObject jObject = JObject.Parse(URLToString(LyURL));

String Lyra = (string)jObject.SelectToken("message.body.lyrics.lyrics_body");

错误信息:HTTP 重定向请求失败

【问题讨论】:

【参考方案1】:

Windows.Web.Http.Headers 命名空间支持创建 HTTP 标头和 cookie,然后将它们作为属性与 HttpRequestMessageHttpResponseMessage 对象关联。请在发送获取请求之前添加header = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)";,如下所示。更多详情请参考document。

public async void SendGetMethod(string url, Action<HttpResponseMessage> resopnse)

    HttpClient client = new HttpClient();
    var headers = client.DefaultRequestHeaders;
    string header = "";
    if (!headers.UserAgent.TryParseAdd(header))
    
        // throw new Exception("Invalid header value: " + header);
    
    header = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)";
    if (!headers.UserAgent.TryParseAdd(header))
    
        throw new Exception("Invalid header value: " + header);
    
    HttpResponseMessage httpResponse = new HttpResponseMessage();
    Uri requestUri = new Uri(url);
    try
    
        httpResponse = await client.GetAsync(requestUri);
        httpResponse.EnsureSuccessStatusCode();
        resopnse(httpResponse);
    
    catch (Exception ex)
    
        Debug.Write("Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message);
    

用法

SendGetMethod("url",(res)=>
                 var result = res
            );

 

【讨论】:

如何使用 HttpResponseMessage 作为操作(顺便说一句,我尝试了文档中的示例,只是应用程序崩溃而没有错误) @AhmedWalid,我发布了用法,请注意您需要使用 Windows.Web.Http 而不是 System.Net.Http【参考方案2】:

我试过这个例子,它对我有用。使用 HttpWebRequest 并设置 CookieContainer 有望解决问题

string url = @"https://apic-desktop.musixmatch.com/ws/1.1/macro.subtitles.get?format=json&q_track=Mi%20Mi%20Mi%20%28Radio%20Edit%29&q_artist=SEREBRO&user_language=en&subtitle_format=mxm&app_id=web-desktop-app-v1.0&usertoken=SECRET TOKEN";

string res;

    HttpWebRequest webReq = (HttpWebRequest)HttpWebRequest.Create(url);
                try
                
                    webReq.CookieContainer = new CookieContainer();
                    webReq.Method = "GET";
                    using (WebResponse response = webReq.GetResponse())
                    
                        using (Stream stream = response.GetResponseStream())
                        
                            StreamReader reader = new StreamReader(stream);
                            res = reader.ReadToEnd();
                          
                    
                
                catch (Exception ex)
                 

【讨论】:

再次尝试它正在工作,也分享了快照。你一定错过了什么。再试一次。

以上是关于UWP C# 项目中的 HTTP 重定向请求失败的主要内容,如果未能解决你的问题,请参考以下文章

CORS 请求重定向失败

尝试将 HTTP 重定向到 HTTPS(C#、IIS),但 HTTPS 在响应标头中转回 HTTP - 重定向循环

HTTP中的重定向和请求转发的区别

带有跨域重定向的 Safari xhr (AJAX) 请求失败

如何正确解码 Java 中的 SAML 请求(HTTP 重定向)?

HTTP2 请求不遵循 JMeter 5.0 中的重定向