今天发现一个接口报错:The remote server returned an error: (302) Bad Request.
分析了一下是调用第三方的时候走auth2认证的流程报错。推测是对方的接口做了调整导致的,之前接口返回httpcode 200,现在httpcode 302(重定向)。
附上之前的请求主要逻辑(C#)
var request = WebRequest.Create(url);
request.Method = "GET";
//在GetResponse的时候抛出了302错误
using (var response = request.GetResponse())
{
string query = response.ResponseUri.Query;
Dictionary<string, string> dic = ParseQueryString(query);
if (dic.ContainsKey("code"))
{
result = dic["code"];
}
}
试了捕获WebException ,也无法获取到Respose的重定向地址
经过研究无耐只能尝试HttpClient的方式请求,修改后的代码:
HttpClientHandler hander = new HttpClientHandler();
hander.AllowAutoRedirect = true;
using (var client = new HttpClient(hander))
{
var res = client.GetAsync(requestUri).Result;
if (res.StatusCode == HttpStatusCode.OK)
{
string query = res.RequestMessage.RequestUri.Query;
Dictionary<string, string> dic = ParseQueryString(query);
if (dic.ContainsKey("code"))
{
result = dic["code"];
}
}
else if (res.StatusCode == HttpStatusCode.Redirect)
{
string query = res.Headers.Location.Query;
Dictionary<string, string> dic = ParseQueryString(query);
if (dic.ContainsKey("code"))
{
result = dic["code"];
}
}
经过测试,发现可以正常获取到重定向的URL了。
事后分析了一下是因为.net core 独有的问题,WebRequest默认不支持重定向,需要自己再模拟重定向的操作。在framework 4.x 就没有问题,默认支持重定向。实属无奈,劝大家给三方提供的接口能不改就尽量不改吧,给大家一个良好的编程环境。
1132

被折叠的 条评论
为什么被折叠?



