我使用下面的代码向服务器发送POST请求:
string url = "http://myserver/method?param1=1¶m2=2"
HttpClientHandler handler = new HttpClientHandler();
HttpClient httpClient = new HttpClient(handler);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
HttpResponseMessage response = await httpClient.SendAsync(request);
Run Code Online (Sandbox Code Playgroud)
我没有访问服务器进行调试,但我想知道,这个请求是以POST还是GET发送的?
如果是GET,如何更改我的代码以将param1和param2作为POST数据发送(不在URL中)?
我正在进行WebCrawler 实现,但在ASP.NET Web API的HttpClient中遇到了奇怪的内存泄漏.
所以减少版本在这里:
我发现了问题,并没有HttpClient泄漏.看我的回答.
我添加了dispose没有效果:
static void Main(string[] args)
{
int waiting = 0;
const int MaxWaiting = 100;
var httpClient = new HttpClient();
foreach (var link in File.ReadAllLines("links.txt"))
{
while (waiting>=MaxWaiting)
{
Thread.Sleep(1000);
Console.WriteLine("Waiting ...");
}
httpClient.GetAsync(link)
.ContinueWith(t =>
{
try
{
var httpResponseMessage = t.Result;
if (httpResponseMessage.IsSuccessStatusCode)
httpResponseMessage.Content.LoadIntoBufferAsync()
.ContinueWith(t2=>
{
if(t2.IsFaulted)
{
httpResponseMessage.Dispose();
Console.ForegroundColor = ConsoleColor.Magenta;
Console.WriteLine(t2.Exception);
}
else
{
httpResponseMessage.Content.
ReadAsStringAsync()
.ContinueWith(t3 =>
{
Interlocked.Decrement(ref waiting);
try
{
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine(httpResponseMessage.RequestMessage.RequestUri); …Run Code Online (Sandbox Code Playgroud) 我已经简化了一些代码,但基本上这一直给我一个"无法访问已处置的对象".错误,我无法解决原因?
我有多个同时运行的任务执行GET,然后解析一些HTML,然后根据GET的结果执行POST.
这段代码所在的方法返回一个带有结果的事件对象,所以我认为我不能使用await,因为该方法需要返回void?
foreach (Account accountToCheck in eventToCheck.accountsToRunOn)
{
Task.Run(() =>
{
HttpClientHandler handler = new HttpClientHandler();
CookieContainer cookies = new CookieContainer();
handler.CookieContainer = cookies;
using (var client = new HttpClient(handler))
{
ServicePointManager.ServerCertificateValidationCallback = delegate (object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
client.Timeout = new TimeSpan(0, 0, 3);
client.DefaultRequestHeaders.Add("Keep-Alive", "false");
HttpResponseMessage response = client.GetAsync("https://test.com", HttpCompletionOption.ResponseContentRead).Result;
string html = response.Content.ReadAsStringAsync().Result;
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("test[username_or_email]", accountToLogIn.accountHandle),
new KeyValuePair<string, string>("test[password]", accountToLogIn.accountPassword)
});
var …Run Code Online (Sandbox Code Playgroud) 作为我正在开发的ASP.Net核心项目的一部分,我需要从WebApi中与许多不同的基于Rest的API端点进行通信.为了实现这一点,我使用了许多服务类,每个服务类都实例化一个静态HttpClient.基本上,我为WebApi连接的每个基于Rest的端点都有一个服务类.
HttpClient下面将看到如何在每个服务类中实例化静态的示例.
private static HttpClient _client = new HttpClient()
{
BaseAddress = new Uri("http://endpointurlexample"),
};
Run Code Online (Sandbox Code Playgroud)
虽然上述方法运行良好,但它不允许对正在使用的服务类进行有效的单元测试HttpClient.为了让我能够进行单元测试,我有一个假的HttpMessageHandler,我想HttpClient在我的单元测试中使用,虽然HttpClient实例化如上,但我不能将假的HttpMessageHandler作为我的单元测试的一部分.
HttpClient服务类在整个应用程序中保持单个实例(每个端点一个实例)的最佳方法是什么,但允许HttpMessageHandler在单元测试期间应用不同的实例?
我想到的一种方法是不使用静态字段来保存HttpClient服务类,而是允许使用单例生命周期通过构造函数注入来注入它,这将允许我在单元测试期间指定一个HttpClient所需的HttpMessageHandler,我想到的另一个选项是使用一个在静态字段HttpClient中实例化HttpClients 的工厂类,然后可以通过将HttpClient工厂注入服务类来检索,再次允许HttpMessageHandler在单元测试中返回相关的不同实现.以上都没有感到特别干净,感觉必须有更好的方法吗?
有任何问题,请告诉我.
c# dotnet-httpclient asp.net-core-mvc .net-core asp.net-core
我知道各种教程以及完整的示例目标WebApi和Entity Framework(甚至来自Microsoft)具有这样的WebApi控制器:
public HttpResponseMessage GetInternet(int id) {
var context = new InternetDbContext();
var result =
(from internet in context.Internets
where internet.Id.Equals(id)
select internet).FirstOrDefault();
if(result != null)
Request.CreateResponse(HttpStatusCode.OK, result);
}
Run Code Online (Sandbox Code Playgroud)
但是,当我了解到Entity Framework像2年前,我每次发现对框架资源指出了它是多么极为重要部署了DbContex在最短可能的寿命与"例如using".而现在,人们似乎并没有放弃处理任何东西(他们的经理,存储库,DI容器......).
我在这里错过了什么吗?API调用的结尾是否会自动处理上下文?或者我必须使用HttpRequestMessageExtensions.RegisterForDispose()来自http://msdn.microsoft.com/en-us/library/dn153859(v=vs.118).aspx的内容?
ASP.Net HttpClient可以部署和很多文章说,你应该使用Singleton模式来使用它,因为的性能,但是当我看到RestClient它不能处理,并在推荐,用法示例页面会new在RestClient每次有什么我的问题我是应该使用单身模式RestClient还是应该new每次使用单一模式,如果我new每次都会出现任何性能问题?
一些参考:
我在nUnit中运行我的测试,通常我可以模拟出依赖项,然后返回某些值或抛出错误.
我有一个类作为内部HttpClient,我想测试该类,我有什么选择.
这是我的代码,它不完整,以免泛滥消息.正如您所看到的,我在内部使用HttpClient而不是作为依赖项注入.该类抛出了许多自定义异常,我想Moq这些,否则我需要传递真实的用户名和密码,这将给我提供我需要抛出异常的状态代码.
有人有想法吗?如果我不能模拟httpclient,那么我永远不会测试我的类,它会引发异常.
我是否真的必须将HttpClient更改为对构造函数的依赖?
public bool ItemsExist(string itemValue)
{
var relativeUri = string.Format(UrlFormatString, itemValue.ToUpper());
var uri = new Uri(new Uri(this.baseUrl), relativeUri);
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", this.encodedCredentials);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetAsync(uri).Result;
switch (response.StatusCode)
{
case HttpStatusCode.Unauthorized:
// DO something here
throw new CustomAuthorizationException();
case HttpStatusCode.Forbidden:
throw new CustomAuthenticationException();
}
return true;
Run Code Online (Sandbox Code Playgroud) 我需要发送以下HTTP发布请求:
POST https://webapi.com/baseurl/login
Content-Type: application/json
{"Password":"password",
"AppVersion":"1",
"AppComments":"",
"UserName":"username",
"AppKey":"dakey"
}
Run Code Online (Sandbox Code Playgroud)
就像上面一样,它在RestClient和PostMan中也很好用。
我需要在语法上做到这一点,并且不确定是否要使用
WebClient,HTTPRequest或WebRequest可以完成此任务。
问题是如何格式化正文内容并在请求中将其发送到上方。
这是我使用WebClient的示例代码的地方...
private static void Main(string[] args)
{
RunPostAsync();
}
static HttpClient client = new HttpClient();
private static void RunPostAsync(){
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
Inputs inputs = new Inputs();
inputs.Password = "pw";
inputs.AppVersion = "apv";
inputs.AppComments = "apc";
inputs.UserName = "user";
inputs.AppKey = "apk";
var res = client.PostAsync("https://baseuriplus", new StringContent(JsonConvert.SerializeObject(inputs)));
try
{
res.Result.EnsureSuccessStatusCode();
Console.WriteLine("Response " + res.Result.Content.ReadAsStringAsync().Result + Environment.NewLine);
}
catch (Exception ex)
{
Console.WriteLine("Error " …Run Code Online (Sandbox Code Playgroud) 我开始 C# 并反序列化 Json。在我的培训中,我学习了 Newtonsoft,但我想对 system.text.json 做同样的事情
有了这个 json,我想选择
制作一个对象列表。
https://api.nvidia.partners/edge/product/search?page=1&limit=9&locale=fr-fr&category=GPU&gpu=RTX%203090,RTX%203080%20Ti,RTX%203080,RTX%203070%20Ti,RTX%203070,RTX%203060%20Ti,RTX%203060&gpu_filter=RTX%203090~12,RTX%203080%20Ti~7,RTX%203080~16,RTX%203070%20Ti~3,RTX%203070~18,RTX%203060%20Ti~8,RTX%203060~2,RTX%202080%20SUPER~1,RTX%202080~0,RTX%202070%20SUPER~0,RTX%202070~0,RTX%202060~6,GTX%201660%20Ti~0,GTX%201660%20SUPER~9,GTX%201660~8,GTX%201650%20Ti~0,GTX%201650%20SUPER~3,GTX%201650~17
Run Code Online (Sandbox Code Playgroud)
班级
public class CarteGraphique
{
public string displayName { get; set; }
public string prdStatus { get; set; }
public List<Retailer> retailers { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
使用 Newtonsoft,我执行以下操作:
牛顿软件
JObject jsonParse = JObject.Parse(json);
IList<CarteGraphique> products = new List<CarteGraphique>();
IList<JToken> productDetailsParse = jsonParse["searchedProducts"]["productDetails"]
.Children()
.Where(n => n["isFounderEdition"].Value<bool>() == true)
.ToList();
var featuredProductParse = jsonParse["searchedProducts"]["featuredProduct"];
foreach (JToken item in productDetailsParse)
{
CarteGraphique result …Run Code Online (Sandbox Code Playgroud) 最初我的代码在每个请求的 using 语句中创建了一个新的 HttpClient 。然后我阅读了几篇关于重用 HttpClient 来提高性能的文章。
这是一篇这样的文章的摘录:
我不建议在 Using 块内创建 HttpClient 来发出单个请求。当 HttpClient 被释放时,它也会导致底层连接也被关闭。这意味着下一个请求必须重新打开该连接。您应该尝试重新使用您的 HttpClient 实例。
http://www.bizcoder.com/httpclient-it-lives-and-it-is-glorious
在我看来,只有当多个请求连续发送到同一个地方时,保持连接打开才有用 - 例如 www.api1.com。
我的问题是,我应该如何创建 HttpClients?
我的网站在后端讨论了大约十种不同的服务。
我应该创建一个 HttpClient 供所有人使用,还是应该为后端使用的每个域创建一个单独的 HttpClient?
示例:如果我与 www.api1.com 和 www.api2.com 交谈,我应该创建 2 个不同的 HttpClient,还是只创建一个 HttpClient?
c# ×10
asp.net-core ×2
httpclient ×2
.net ×1
.net-core ×1
asp.net ×1
json ×1
memory-leaks ×1
mocking ×1
moq ×1
nunit ×1
parameters ×1
post ×1
restsharp ×1