我正在寻找一种方法来处理需要登录的API,然后重定向到另一个URL 问题是到目前为止,我只想出办法为我想要做的每个动作制作2个Http请求:首先,使用AllowRedirect = false获取cookie,然后获取实际的URI并使用cookie执行第二个请求:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sUrl);
request.AllowAutoRedirect = false;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string redirectedUrl = response.Headers["Location"];
if (!String.IsNullOrEmpty(redirectedUrl))
{
redirectedUrl = "http://www.ApiUrlComesHere.com/" + redirectedUrl;
HttpWebRequest authenticatedRequest = (HttpWebRequest)WebRequest.Create(redirectedUrl);
authenticatedRequest.Headers["Cookie"] = response.Headers["Set-Cookie"];
response = (HttpWebResponse)request.GetResponse();
}
看起来非常低效。有另一种方式吗?
谢谢!
答案 0 :(得分:1)
public String Post(String url, IDictionary<String, String> data)
{
String requestData = String.Join("&", data.Select(x => String.Format("{0}={1}", HttpUtility.UrlEncode(x.Key), HttpUtility.UrlEncode(x.Value))));
Byte[] requestBytes = Encoding.UTF8.GetBytes(requestData);
CookieContainer cookies = new CookieContainer();
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.CookieContainer = cookies;
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = requestBytes.Length;
request.AllowAutoRedirect = false;
Stream requestStream = request.GetRequestStream();
requestStream.Write(requestBytes, 0, requestBytes.Length);
requestStream.Close();
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
while (response.StatusCode == HttpStatusCode.Found)
{
response.Close();
String location = response.Headers[HttpResponseHeader.Location];
request = WebRequest.Create(location) as HttpWebRequest;
request.CookieContainer = cookies;
request.Method = WebRequestMethods.Http.Get;
response = request.GetResponse() as HttpWebResponse;
}
String responseData = this.Read(response.GetResponseStream());
response.Close();
return (responseData);
}
答案 1 :(得分:0)
看起来非常低效。
为什么?
最后,这只是HttpWebRequest
,AllowAutoRedirect true
即可。