Set user-agent header during HTTP CONNECT over SSL?
I am using the WebClient class in .NET 2.0 to perform an HTTP POST over SSL.
Currently I'm manually setting the user-agent header like so:
wc = new WebClient();
wc.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
This works fine, except for when I make the request through a proxy server that does HTTP tunnelling and expects a specific user-agent header in the HTTP CONNECT command.
When a proxy acts as a tunnel for SSL, it initially recieves an HTTP CONNECT which tells it where the client is trying to con开发者_JAVA百科nect to.
The problem is that if you set the user-agent header in .NET either via HttpWebRequest.UserAgent, or WebClient.Headers.Add, it does not add it to the initial CONNECT request. It does add it to subsequent SSL traffic, but that's not what is needed.
If this was C++ I would simply call WinHttpOpen() to create the sesson and set the pwszUserAgent param to set the user agent for the whole session. Unfortunately I cannot find an equivalent in .NET.
Can anyone point me in the right direction? I'm sure that someone else must have come across this problem building client apps in .NET.
You will not be able to send the User-Agent header using the HttpWebRequest family of classes. The RFCs say that the header is optional (SHOULD rather than MUST)
You could add a rule to the proxy to allow connections out with no User-Agent header, or for particular target servers, or finally code your own HTTP Protocol using the .NET Socket Classes.
Try with HttpWebRequest (framework 2.0):
HttpWebRequest httpReq = HttpWebRequest.Create(new Uri("www.website.com"));
httpReq.Headers["user-agent"] = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)";
I'm using it with Windows Phone 7 sdk and it works.
For more info: http://msdn.microsoft.com/en-gb/library/system.net.httpwebrequest(v=vs.80).aspx
Setting the proxy should be enough
WebClient client = new WebClient();
client.Headers["User-Agent"] =
"Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0) " +
"(compatible; MSIE 6.0; Windows NT 5.1; " +
".NET CLR 1.1.4322; .NET CLR 2.0.50727)";
client.Proxy = new WebProxy(your_proxy_url, true);
your_proxy_url could be like http://proxy.company.com:8080/
精彩评论