将curl转换为http请求并在C#中获取响应

时间:2016-05-12 01:26:03

标签: c# http curl request

我是C#的新手,我想在我的C#中进行以下curl调用(在perl中我会直接使用系统调用来调用curl请求)

curl 'http://shop.nordstrom.com/soajax/storeavailability?postalCode=90067&radius=100' -H 'Origin: http://shop.nordstrom.com' -H 'Accept-Encoding: gzip, deflate' -H 'Accept-Language: en-US,en;q=0.8' -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 'Content-Type: application/json' -H 'Accept: application/json' -H 'Referer: http://shop.nordstrom.com/s/cece-by-cynthia-steffe-jackie-cold-shoulder-fit-flare-dress/4261930' --data-binary '{"SameDayDeliveryStoreNumber":0,"styleSkus":[{"StyleId":4261930,"SkuIds":[32882914,32877390,32877377,32882917,32882922,32882926,32877379,32882887,32882891,32877382,32882897,32882902,32882907,32882909]}],"RefreshSameDayDeliveryStore":true}' --compressed

首先,如何将所有参数更改为http,以便我可以在浏览器中查看响应

然后我可以将cURL调用转换为HTTP请求吗?如果是这样,怎么样?如果没有,我如何从我的C#程序中进行上述cURL调用,以便我得到正确的响应?

1 个答案:

答案 0 :(得分:1)

只需制作HttpWebRequest

var url = "http://shop.nordstrom.com/soajax/storeavailability?postalCode=90067&radius=100";
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = WebRequestMethods.Http.Post;
request.Headers["origin"] = "http://shop.nordstrom.com";
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
request.Headers["Accept-Language"] = "en-US,en;q=0.8";
request.UserAgent = "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";
request.ContentType = "application/json";
request.Accept = "application/json";
request.Referer = "http://shop.nordstrom.com/s/cece-by-cynthia-steffe-jackie-cold-shoulder-fit-flare-dress/4261930";
using (var writer = new StreamWriter(request.GetRequestStream()))
{
    writer.Write("{\"SameDayDeliveryStoreNumber\":0,\"styleSkus\":[{\"StyleId\":4261930,\"SkuIds\":[32882914,32877390,32877377,32882917,32882922,32882926,32877379,32882887,32882891,32877382,32882897,32882902,32882907,32882909]}],\"RefreshSameDayDeliveryStore\":true}");
}

var response = request.GetResponse();
using (var reader = new StreamReader(response.GetResponseStream()))
{
    var json = reader.ReadToEnd();
    // do stuffs...
}