我想用Fiddler检查http流量,但是没有捕获到任何http流量,我的测试代码:
private static void ByRestSharp()
{
var restClient = new RestClient("https://jsonplaceholder.typicode.com");
var request = new RestRequest("posts", Method.GET);
var response = restClient.Get<List<Post>>(request);
Console.WriteLine("{0} posts return by RestSharp.", response.Data.Count);
}
但是我改用HttpClient后,Fiddler就可以抓取http流量了,示例代码:
private static void ByHttpClient()
{
var httpClient = new HttpClient();
using (var req = new HttpRequestMessage(HttpMethod.Get, "https://jsonplaceholder.typicode.com/posts"))
using (var resp = httpClient.SendAsync(req).Result)
{
var json = resp.Content.ReadAsStringAsync().Result;
var users = SimpleJson.SimpleJson.DeserializeObject<List<Post>>(json);
Console.WriteLine("{0} posts return by HttpClient.", users.Count);
}
}
这是RestSharp还是Fiddler的问题?
RestSharp 支持系统代理,直到我们迁移到 .NET Standard。然后,我们在 .NET Core 上遇到了代理问题,然后完全删除了系统代理。我们在 Github 上打开了一个 issue,您可以在那里查看进度。
但是,显式设置代理应该适用于完整的 .NET Framework,请检查此问题。
问题中的代码,已确认有效:
var client = new RestClient("http://www.google.com");
client.Proxy = new WebProxy("127.0.0.1", 8888);
var req = new RestRequest("/", Method.GET);
var resp = client.Execute(req);
更新 2018-05-31: RestSharp 106.3 也会自动使用 .NET Core 上的默认代理。使用 Fiddler 进行测试。
2022 年 2 月 23 日更新: RestSharp 107 将 Proxy
属性移至
RestClientOptions
:
var options = new RestClientOptions("http://www.google.com") {
Proxy = new WebProxy("127.0.0.1", 8888)
};
var client = new RestClient(options);
var req = new RestRequest("/");
var resp = await client.ExecuteAsync(req);
var proxy = GetWebProxy();//your IWebProxy factory
var httpClientHandler = new HttpClientHandler()
{
Proxy = proxy,
};
using (var dataClient = new RestClient(httpClientHandler))
{
...
}