如何发出GET类型的RESTful请求

3

我需要在URL中包含curl -H 'Context-type:application/json',但不确定如何实现。目前服务器响应为404,非常感谢任何帮助。

private string RequestVehicleData()
        {
            string make = "";
            string postcode = "";

            string registration = (string)(Session["regNo"]);
            make = txtmake.Text;
            postcode = txtpostcode.Text;


            //Make Request
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(string.Format("https://www.check-mot.service.gov.uk/api/v1/mot-history/{0}/{1}/", registration, make));
            httpWebRequest.ContentType = "application/json";                      
            httpWebRequest.Method = "GET";


            //Get Response
            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
                return result;
            }
        }

1
可能是重复的问题:如何在C#中设置HttpWebRequest的内容? - Paul Swetz
1个回答

1

尝试使用HttpClient。以下是从MSDN复制的示例:http://www.asp.net/web-api/overview/advanced/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);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接