这是我到目前为止的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System;
using System.Net.Http;
using System.Web;
using System.Net;
using System.IO;
namespace ConsoleProgram
{
public class Class1
{
private const string URL = "https://sub.domain.com/objects.json?api_key=123";
private const string DATA = @"{""object"":{""name"":""Name""}}";
static void Main(string[] args)
{
Class1.CreateObject();
}
private static void CreateObject()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = DATA.Length;
StreamWriter requestWriter = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
requestWriter.Write(DATA);
requestWriter.Close();
try {
WebResponse webResponse = request.GetResponse();
Stream webStream = …Run Code Online (Sandbox Code Playgroud) 这是我正在使用的代码:
// create a request
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create(url); request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";
// turn our request string into a byte stream
byte[] postBytes = Encoding.UTF8.GetBytes(json);
// this is important - make sure you specify type this way
request.ContentType = "application/json; charset=UTF-8";
request.Accept = "application/json";
request.ContentLength = postBytes.Length;
request.CookieContainer = Cookies;
request.UserAgent = currentUserAgent;
Stream requestStream = request.GetRequestStream();
// now send it
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
// grab te response and print it out …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用web api HttpClient对端点进行发布,该端点需要以标识帐户的HTTP cookie的形式登录(这只是#ifdef发布版本之外的内容).
如何添加cookie HttpRequestMessage?
HttpClientWebAPI客户端的生命周期应该是多少?为多个调用
设置一个实例是否更好HttpClient?
创建和处理HttpClient每个请求的开销是多少,如下面的示例所示(摘自http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from- a-net-client):
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:9000/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// New code:
HttpResponseMessage response = await client.GetAsync("api/products/1");
if (response.IsSuccessStatusCode)
{
Product product = await response.Content.ReadAsAsync<Product>();
Console.WriteLine("{0}\t${1}\t{2}", product.Name, product.Price, product.Category);
}
}
Run Code Online (Sandbox Code Playgroud) 在我可以找到的所有示例中HttpClient,它用于一次性呼叫.但是,如果我有一个持久的客户端情况,可以同时进行多个请求怎么办?基本上,client.PostAsync对同一个实例一次调用2个线程是安全的HttpClient.
我不是在寻找实验结果.作为一个工作示例可能只是一个侥幸(并且持久的),一个失败的例子可能是一个错误的配置问题.理想情况下,我正在寻找HttpClient中并发处理问题的一些权威答案.
所有:
在向Web服务发送请求之前,我需要将http标头添加到HttpClient.我如何为单个请求执行此操作(而不是将HttpClient应用于所有将来的请求)?我不确定这是否可行.
var client = new HttpClient();
var task =
client.GetAsync("http://www.someURI.com")
.ContinueWith((taskwithmsg) =>
{
var response = taskwithmsg.Result;
var jsonTask = response.Content.ReadAsAsync<JsonObject>();
jsonTask.Wait();
var jsonObject = jsonTask.Result;
});
task.Wait();
Run Code Online (Sandbox Code Playgroud) // let's say there is a list of 1000+ URLs
string[] urls = { "http://google.com", "http://yahoo.com", ... };
// now let's send HTTP requests to each of these URLs in parallel
urls.AsParallel().ForAll(async (url) => {
var client = new HttpClient();
var html = await client.GetStringAsync(url);
});
Run Code Online (Sandbox Code Playgroud)
这是问题所在,它会同时启动1000多个Web请求.有没有一种简单的方法来限制这些异步http请求的并发数量?这样在任何给定时间都不会下载超过20个网页.如何以最有效的方式做到这一点?
我正在使用它System.Net.Http.HttpClient做一些客户端HTTP通信.我在一个地方得到了所有的HTTP,从其余的代码中抽象出来.在一个实例中,我想将响应内容作为流读取,但是流的使用者与HTTP通信发生的位置以及流被打开的情况很好地隔离.在负责HTTP通信的地方我处理所有的HttpClient东西.
此单元测试将失败Assert.IsTrue(stream.CanRead):
[TestMethod]
public async Task DebugStreamedContent()
{
Stream stream = null; // in real life the consumer of the stream is far away
var client = new HttpClient();
client.BaseAddress = new Uri("https://www.google.com/", UriKind.Absolute);
using (var request = new HttpRequestMessage(HttpMethod.Get, "/"))
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
//here I would return the stream to the caller
stream = await response.Content.ReadAsStreamAsync();
}
Assert.IsTrue(stream.CanRead); // FAIL if response is disposed so is the stream …Run Code Online (Sandbox Code Playgroud) 我很好奇这HttpClientFactory堂课的目的是什么.没有描述MSDN上存在的原因(参见链接).
有些Create方法有更专业的参数,但大多数我不知道没有参数的调用和普通的构造函数之间有什么区别.
var httpClient = HttpClientFactory.Create();
Run Code Online (Sandbox Code Playgroud)
VS
var httpClient = new HttpClient();
Run Code Online (Sandbox Code Playgroud)
在大多数示例中,我看到使用了new HttpClient(),没有任何using语句,即使HttpClient该类派生自IDisposable.
由于HttpClient该类源自IDisposable,工厂是否有一些池化或缓存?是否有性能优势,或者无关紧要?
我使用下面的代码向服务器发送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中)?
c# ×8
.net ×3
post ×2
rest ×2
api ×1
asp.net ×1
async-await ×1
async-ctp ×1
asynchronous ×1
c#-4.0 ×1
concurrency ×1
httpclient ×1
idisposable ×1
json ×1
parameters ×1
stream ×1
web-services ×1