WindowsRuntime一次设置User-Agent无须每次请求修改User-Agent
WindowsRuntime一次设置User-Agent无须每次请求修改User-Agent
public static class UserAgent
{
const int URLMON_OPTION_USERAGENT = 0x10000001;
[DllImport("urlmon.dll", CharSet = CharSet.Ansi)]
private static extern int UrlMkSetSessionOption(int dwOption, string pBuffer, int dwBufferLength, int dwReserved);
[DllImport("urlmon.dll", CharSet = CharSet.Ansi)]
private static extern int UrlMkGetSessionOption(int dwOption, StringBuilder pBuffer, int dwBufferLength, ref int pdwBufferLength, int dwReserved);
public static string GetUserAgent()
{
int capacity = 255;
var buf = new StringBuilder(capacity);
int length = 0;
UrlMkGetSessionOption(URLMON_OPTION_USERAGENT, buf, capacity, ref length, 0);
return buf.ToString();
}
public static void SetUserAgent(string agent)
{
var hr = UrlMkSetSessionOption(URLMON_OPTION_USERAGENT, agent, agent.Length, 0);
var ex = Marshal.GetExceptionForHR(hr);
if (null != ex)
{
throw ex;
}
}
public static void AppendUserAgent(string suffix)
{
SetUserAgent(GetUserAgent() + suffix);
}
}
然后在应用启动位置使用
UserAgent.SetUserAgent("Mozilla/5.0 (Windows Phone 10.0; Android 6.0.1; WebView/3.0; Microsoft; Lumia 950) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Mobile Safari/537.36 Edge/15.15254");