在创建HttpClient对象时,HttpClientHandler可以用作参数,但之后似乎没有任何方法可以在不保留对它的引用的情况下访问处理程序。
Dim Handler as New HttpClientHandler
Handler.CookieContainer = Cookies
Handler.Proxy = Proxy
Handler.UseProxy = True
Handler.AutomaticDecompression = DecompressionMethods.GZip Or DecompressionMethods.Deflate
Dim Client as New HttpClient(Handler, True)
我能够更改现有客户端对象的处理程序的属性吗?例如,更改代理服务器或AutoRedirect。当客户端当前正在处理其他HttpRequestMessages时,我是否会遇到任何问题?
答案 0 :(得分:1)
经过进一步测试似乎不可能,当我尝试修改HttpClientHandler的属性时会抛出异常。需要一个新的HttpClient实例。
答案 1 :(得分:1)
是的,你可以。关键是要更改对象而不是httpclient的属性。记住OOP 101。
将属性指向同一个对象,但更改该对象的内容。
Dim Handler As New HttpClientHandler
Dim proxy As New WebProxy()
Dim urlBuilder As New System.UriBuilder
Handler.Proxy = proxy
Handler.UseProxy = True
Handler.AutomaticDecompression = DecompressionMethods.GZip Or DecompressionMethods.Deflate
Dim Client As New HttpClient(Handler, True)
urlBuilder.Host = "124.161.94.8"
urlBuilder.Port = 80
proxy.Address = urlBuilder.Uri
Dim response As String = Await Client.GetStringAsync("http://www.ipchicken.com")
urlBuilder.Host = "183.207.228.8"
urlBuilder.Port = 80
proxy.Address = urlBuilder.Uri
response = Await Client.GetStringAsync("http://www.ipchicken.com")