如何在C#

时间:2016-05-26 13:22:57

标签: c# curl

如何在Windows或

中的c#中发出curl请求

我想使用此参数发出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

在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`;

然后

my $page

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

如何在c#中做同样的事情

2 个答案:

答案 0 :(得分:2)

我强烈建议您使用新的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);
 }

答案 1 :(得分:1)

使用HttpWebRequest E.g。

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();
}

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