I want use HttpClient
set useragent like this
"Dalvik/2.1.0 (Linux; U; Android 5.1.1; YAL-AL10 Build/LMY48Z) [something]"
But useragent not allowed symbol []
Any one know how to fix this ?
httpRequestMessage.Headers.Add("User-Agent", "myCustomUserAgent [xx]");
will throw exception
在 System.Net.Http.Headers.HttpHeaderParser.ParseValue(String value, Object storeValue, Int32& index)
在 System.Net.Http.Headers.HttpHeaders.ParseAndAddValue(String name, HeaderStoreItemInfo info, String value)
在 System.Net.Http.Headers.HttpHeaders.Add(String name, String value)
在 Facebook_scan.Form1.<ttt>d__39.MoveNext() 在 D:\c#\Facebook_scan\Facebook_scan\Form1.cs 中: 第 237 行
If you really need to do this... I guess you could use TryAddWithoutValidation
if HttpClient is being overly constrictive parsing headers
Returns a value that indicates whether a new header and its values were added to the
HttpHeaders
collection without validating the provided information.
var funkyUserAgent = "Dalvik/2.1.0 (Linux; U; Android 5.1.1; YAL-AL10 Build/LMY48Z) [something]"
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", funkyUserAgent);
// or
var httpRequestMessage = new HttpRequestMessage();
httpRequestMessage.Headers.TryAddWithoutValidation("User-Agent", funkyUserAgent);
Note : You should really be checking the return value :)
Example
var httpClient = new HttpClient();
var funkyUserAgent = "Dalvik/2.1.0 (Linux; U; Android 5.1.1; YAL-AL10 Build/LMY48Z) [something]";
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "https://postman-echo.com/headers");
httpRequestMessage.Headers.TryAddWithoutValidation("User-Agent", funkyUserAgent);
var result = await httpClient.SendAsync(httpRequestMessage);
var content = await result.Content.ReadAsStringAsync();
Console.WriteLine(content);
Output
{
"headers":{
"x-forwarded-proto":"https",
"x-forwarded-port":"443",
"host":"postman-echo.com",
"x-amzn-trace-id":"Root=1-5fcf4709-35d9a93c0e1703920c572b7e",
"user-agent":"Dalvik/2.1.0 (Linux; U; Android 5.1.1; YAL-AL10 Build/LMY48Z) [something]"
}
}