Can I change the properties of a HttpClientHandler after the HttpClient has been created?

社会主义新天地 提交于 2021-02-08 06:13:24

问题


The HttpClientHandler can be used as a parameter when creating a HttpClient object, but after that there doesn't seem to be any way to access the handler without keeping a reference to it.

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)

Am I able to change the properties of a handler of an existing client object? For example, change the Proxy or the AutoRedirect. Would I have any issues doing this while other HttpRequestMessages are currently being processed by the client?


回答1:


Yes, you can. The key is to change the object and not the property of the httpclient. Remember OOP 101.

Point the property to the same object but change the contents of that object.

 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")



回答2:


After further testing it seems it is not possible, an exception is thrown when I attempt to modify the properties of the HttpClientHandler. A new instance of HttpClient is required.



来源:https://stackoverflow.com/questions/25795777/can-i-change-the-properties-of-a-httpclienthandler-after-the-httpclient-has-been

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!