【问题标题】:How to make a GET RESTful Request如何发出 GET RESTful 请求
【发布时间】:2016-11-08 11:01:57
【问题描述】:

我需要在 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;
            }
        }

【问题讨论】:

标签: c#


【解决方案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);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-25
    • 2018-11-19
    • 1970-01-01
    • 1970-01-01
    • 2020-12-25
    • 2012-06-14
    • 2019-11-09
    相关资源
    最近更新 更多