如何使用 HttpClient 从特定 IP 地址发送请求?C# [英] How to use HttpClient to send a Request from a specific IP address? C#
问题描述
我在服务器上有多个 IP,并且想在使用 HttpClient 类从 API 获取/发布数据时选择要使用的 IP.(或者甚至同时发送请求,但使用 2 个 IP 而不仅仅是一个)
I have multiple IPs on the server and would like to chose which one of those I want to use when using HttpClient class to get/post data from an API. (or to even send requests at the same time but utilise the 2 IPs and not just one)
我见过一些使用 HttpWebRequest 的例子(here) 使用委托,但我想继续使用 HttpClient 实现.
I have seen some examples using HttpWebRequest (here) that utilises delegate but I would like to carry on using HttpClient implementation.
推荐答案
[ 这将是一个 hacky 代码,因为没有方法/属性可以访问 ServicePoint ]
[ This will be a hacky code, because there is no method/property to access the ServicePoint ]
您可以使用反射访问底层ServicePoint,如下所示(由于没有公共/私有字段/属性来访问这个值,我将钩住startRequest委托)
You can use reflection to access the underlying ServicePoint as below (Since there is no public/private field/property to access this value, I will hook the startRequest delegate)
HttpClientHandler SetServicePointOptions(HttpClientHandler handler)
{
var field = handler.GetType().GetField("_startRequest", BindingFlags.NonPublic| BindingFlags.Instance); // Fieldname has a _ due to being private
var startRequest = (Action<object>)field.GetValue(handler);
Action<object> newStartRequest = obj =>
{
var webReqField = obj.GetType().GetField("webRequest", BindingFlags.NonPublic | BindingFlags.Instance);
var webRequest = webReqField.GetValue(obj) as HttpWebRequest;
webRequest.ServicePoint.BindIPEndPointDelegate = new BindIPEndPoint(BindIPEndPointCallback);
startRequest(obj); //call original action
};
field.SetValue(handler, newStartRequest); //replace original 'startRequest' with the one above
return handler;
}
BindIPEndPointCallback 是您链接 在您的问题中.根据需要修改它.现在你可以像
BindIPEndPointCallback is the one you linked in your question. Modify it as you wish. Now you can use this method like
HttpClientHandler handler = SetServicePointOptions(new HttpClientHandler());
HttpClient client = new HttpClient(handler);
var str = await client.GetStringAsync("https://google.com");
这篇关于如何使用 HttpClient 从特定 IP 地址发送请求?C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!