C# Android:如何将WebView登录凭据传递到HttpWebRequest?
我正在尝试将登录凭据从C# Android:如何将WebView登录凭据传递到HttpWebRequest?,c#,authentication,webview,xamarin.android,httprequest,C#,Authentication,Webview,Xamarin.android,Httprequest,我正在尝试将登录凭据从WebView传递到HttpWebRequest中,但没有得到经过身份验证的响应。我能够成功地发出请求,但响应好像我还没有登录。我的应用程序有5个WebViews包含在Fragments中,我已经登录了它们。我尝试过使用CookieSyncManager,但它已被弃用,而且.Sync()不起作用。我尝试了很多不同的方法将cookies传递到HttpRequest中,但都没有成功,而且花费了很多时间 有人会认为这是一个简单的要求;用户已在应用程序内登录;应该对所有请求进行身份
WebView
传递到HttpWebRequest
中,但没有得到经过身份验证的响应。我能够成功地发出请求,但响应好像我还没有登录。我的应用程序有5个WebViews
包含在Fragment
s中,我已经登录了它们。我尝试过使用CookieSyncManager
,但它已被弃用,而且.Sync()
不起作用。我尝试了很多不同的方法将cookies传递到HttpRequest
中,但都没有成功,而且花费了很多时间
有人会认为这是一个简单的要求;用户已在应用程序内登录;应该对所有请求进行身份验证。这是我得到的最接近的结果,但是响应字符串仍然与通过身份验证的WebView
得到的不一样:
此尝试将每个Cookie
解析为一个字符串并添加它
public string _cookieString { get; set; }
private class ExtWebViewClient : WebViewClient
{
TheFragment5 _fm5 = new TheFragment5();
public override void OnPageFinished(WebView view, string url)
{
var cookieHeader = Android.Webkit.CookieManager.Instance.GetCookie(url);
var cookiePairs = cookieHeader.Split('&');
_fm5._cookieString = "";
foreach (var cookiePair in cookiePairs)
{
var cookiePieces = cookiePair.Split('=');
if (cookiePieces[0].Contains(":"))
cookiePieces[0] = cookiePieces[0].Substring(0, cookiePieces[0].IndexOf(":"));
cookies.Add(new Cookie
{
Name = cookiePieces[0],
Value = cookiePieces[1]
});
}
foreach (Cookie c in cookies)
{
if (_fm5._cookieString == "")
{
_fm5._cookieString = c.ToString();
}
else
{
_fm5._cookieString += c.ToString();
}
}
}
}
我也尝试过这样做:
_fm5._cookieString = cookieHeader.ToString();
但是,当我将cookie字符串添加到我的HttpRequest
中时,这两种尝试都不起作用:
public async void GetNotificationText(string url)
{
//var _cmhc = _cookieMan.HasCookies;
await Task.Run(() =>
{
_notificationHttpRequestInProgress = true;
try
{
var _ctxxx = Android.App.Application.Context;
//URL _url2 = new URL("https://bitchute.com/notifications/");
//HttpURLConnection conn = (HttpURLConnection)_url2.OpenConnection();
//conn.ReadTimeout = 10000 /* milliseconds */;
//conn.ConnectTimeout = 15000 /* milliseconds */;
////conn.SetRequestProperty("Cookie", cookies);
//conn.Connect();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
Uri uri = new Uri(url);
var _req = request;
var _uriii = uri;
var _cookiesss = _fm5._cookieString;
_cookieCon.SetCookies(uri, _cookiesss);
request.CookieContainer = _cookieCon;
//request.CookieContainer.SetCookies(uri, _cookiesss);
request.AutomaticDecompression = DecompressionMethods.GZip;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
_notificationRawText = reader.ReadToEnd();
Console.WriteLine(_notificationRawText);
_rawNoteText = _notificationRawText;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
_notificationHttpRequestInProgress = false;
});
}
这将返回但不返回经过身份验证的webtext请求;我得到的响应与从未登录过的用户在浏览器上得到的响应相同。如果我在我的应用程序中的任何WebView
上浏览到相同的url,我会得到完全不同的响应
您还将注意到一些注释掉的代码,这是将cookie添加到连接中的另一次失败尝试。我还尝试过使用HttpURLConnection.SetRequestProperty(“Cookie”,cookies)代码>
其中cookies是一个CookieCollection
,这也不起作用。代码大部分被注释掉并分层,因为我已经尝试了好几天了
有人知道我如何使用Xamarin.Android将WebView
cookies传递到HttpRequest
中吗
我将此代码放在我的应用程序的Fragment5
下面;您可以在此处查看并编译完整的上下文:
我不清楚上面的例子为什么不起作用;也许如果你比我更擅长.NET,你会明白的。但是,通过执行以下步骤,我能够成功地将WebView
creds传递到HttpClient
,这些步骤将返回经过身份验证的响应。这可能不是最优雅的方式,但你可以随时完善我的答案,或张贴一个更好的
我要做的是使用.Add()
方法设置HttpClient.DefaultRequestHeaders
,如下所示:\u client.DefaultRequestHeaders.Add(“Cookie”,TheFragment5.\u cookieHeader)代码>
我得到了CookieHeader(它只是一个字符串
btw),如下所示:
//instantiate a string that will house our cookie header
public static string _cookieHeader;
//you might want to make it private to prevent abuse
//but this example is just for demonstration
//the thing is we need a string to house our headers in scope of both the WebView and the HttpClient
//extend the WebViewClient
private class ExtWebViewClient : WebViewClient
{
public override void OnPageFinished(WebView view, string url)
{
//I get the cookies when the page finishes loading because
//then we know the cookie has our login cred header
//also, most of the previous examples got the cookies OnPageFinished
TheFragment5._cookieHeader = Android.Webkit.CookieManager.Instance.GetCookie(url);
}
}
然后我们需要为HttpClient
和HttpClientHandler
提供另一种方法。。。地雷扫描网页的通知文本
public async void GetNotificationText(string url)
{
await Task.Run(() =>
{
/* this line is pretty important,
we need to instantiate an HttpClientHandler
then set it's UseCookies property to false
so that it doesn't override our cookies
*/
HttpClientHandler handler = new HttpClientHandler() { UseCookies = false };
try
{
Uri _notificationURI = new Uri("https://bitchute.com/notifications/");
//instantiate HttpClient using the handler
using (HttpClient _client = new HttpClient(handler))
{
//this line is where the magic happens;
//we set the DefaultRequestHeaders with the cookieheader we got from WebViewClient.OnPageFinished
_client.DefaultRequestHeaders.Add("Cookie", TheFragment5._cookieHeader);
//do a GetAsync request with our cookied up client
var getRequest = _client.GetAsync("https://bitchute.com/notifications/").Result;
//resultContent is the authenticated html string response from the server, ready to be parsed =]
var resultContent = getRequest.Content.ReadAsStringAsync().Result;
/*
I was writing to console to check the
response.. for me, I am now getting
the authenticated notification html
page
*/
Console.WriteLine(resultContent);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
希望这对您有所帮助,特别是对于使用Xamarin.Android的用户,以供将来参考。,如果您想从webview获取cookie并在httpclient中设置,我建议您可以看一看:我试过了,但没有成功。这可能与Xamarin.Android没有CookieStore这一事实有关?谢谢你的回复!