如何在C#中发出HTTP请求

Mou*_*jan 5 c# curl

我如何在Windows中的C#中发出卷曲请求

我想使用此参数发出Web请求,并且它应该收到有效的响应

请求

curl 'http://www1.bloomingdales.com/api/store/v2/stores/367,363,6113,364,4946?upcNumber=808593890516' -H 'Cookie:shippingCountry=US;' -H 'Accept-Encoding: gzip, deflate, sdch' -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/49.0.2623.108 Chrome/49.0.2623.108 Safari/537.36' -H 'Accept-Language: en-US,en;q=0.8' -H 'Accept: application/json, text/javascript, */*; q=0.01' --compressed
Run Code Online (Sandbox Code Playgroud)

在perl中,我只会做

my $page = `curl --silent 'http://www1.bloomingdales.com/api/store/v2/stores/367,363,6113,364,4946?upcNumber=808593890516' -H 'Cookie:shippingCountry=US;' -H 'Accept-Encoding: gzip, deflate, sdch' -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/49.0.2623.108 Chrome/49.0.2623.108 Safari/537.36' -H 'Accept-Language: en-US,en;q=0.8' -H 'Accept: application/json, text/javascript, */*; q=0.01' --compressed 2>/dev/null`;
Run Code Online (Sandbox Code Playgroud)

然后

my $page
Run Code Online (Sandbox Code Playgroud)

结果存储在上面的变量中。

如何在C#中类似地做?

Eri*_*ips 7

我强烈建议使用新的HttpClient

请阅读此答案底部的注释

摘自 MSDN。

static async void Main()
{

    // Create a New HttpClient object.
    HttpClient client = new HttpClient();

    // Call asynchronous network methods in a try/catch block to handle exceptions
    try 
    {
       HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");
       response.EnsureSuccessStatusCode();
       string responseBody = await response.Content.ReadAsStringAsync();
       // Above three lines can be replaced with new helper method below
       // string responseBody = await client.GetStringAsync(uri);

       Console.WriteLine(responseBody);
    }  
    catch(HttpRequestException e)
    {
       Console.WriteLine("\nException Caught!");    
       Console.WriteLine("Message :{0} ",e.Message);
    }

    // Need to call dispose on the HttpClient object
    // when done using it, so the app doesn't leak resources
    client.Dispose(true);
 }
Run Code Online (Sandbox Code Playgroud)

由于这个答案最初是写的,所以有一些关于使用 HttpClient 的警告。(TLDR;它应该是一个单身人士)

按预期使用 HttpClient(因为您不是)

在 WebAPI 客户端中为每次调用创建一个新的 HttpClient 的开销是多少?

您错误地使用了 HTTPClient,它正在破坏您的软件的稳定性


loo*_*ode 0

使用HttpWebRequest 例如

HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://www.google.com");
// access req.Headers to get/set header values before calling GetResponse. 
// req.CookieContainer allows you access cookies.

var response = req.GetResponse();
string webcontent;
using (var strm = new StreamReader(response.GetResponseStream()))
{
    webcontent = strm.ReadToEnd();
}
Run Code Online (Sandbox Code Playgroud)

您可以通过访问请求对象的HeadersCookieContainer属性来根据请求设置 headers/cookie。您还可以访问响应对象的各种属性来获取各种值。