【问题标题】:Using LibCurlNet to make an authenticated http get request from json rest API使用 LibCurlNet 从 json rest API 发出经过身份验证的 http get 请求
【发布时间】:2011-09-17 20:39:24
【问题描述】:

cURL 请求、webrequest 或任何消费方式:

小黄鸟在我头上飞来飞去,因为我从未在 asp.net 中使用过 cURL;我想要实现的(希望这也是明智的)是使用 LibCurlNet dlls 以便使用我给定的用户名和密码向Police API 发出简单的获取请求。

使用这个每个请求都必须包含您的 API 用户名和密码。卷曲示例:

curl -u username:password http://policeapi2.rkh.co.uk/api/forces

API 使用 HTTP GET 请求实现为标准 JSON REST Web 服务。

我希望有一个像 webmethod 这样的 c# 类,以便通过 ajax 调用使用 jquery 从 API 中检索信息。

我知道如何制作 web 方法,但我不知道如何将它与 LibCurlNet 结合。

我对 LibCurlNet 喋喋不休的唯一原因不是我喜欢它,所以如果你认为我应该使用不同的方法来使用这个 API 中的数据,请这样做。

请让我知道我是否可以提供任何使这一点更清楚的信息。

非常感谢

【问题讨论】:

    标签: jquery asp.net json curl restful-authentication


    【解决方案1】:
    public const String LocalCrime = http://policeapi2.rkh.co.uk/api/leicestershire/C01/crime";
    
    [WebMethod(true)]
    public static String request()
    {
        // Initialize the WebRequest.
        WebRequest myRequest = WebRequest.Create(LocalCrime);
    
        myRequest.ContentType = "application/x-www-form-urlencoded";
        myRequest.Credentials = new NetworkCredential("username", "password");
        // Return the response. 
        WebResponse myResponse = myRequest.GetResponse();
        StringBuilder _Content = new StringBuilder();
        using (StreamReader _Reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8))
        {
            _Content.Append(_Reader.ReadToEnd());
        }
        // Code to use the WebResponse goes here.
    
        // Close the response to free resources.
        myResponse.Close();
        return _Content.ToString();
    }
    

    带脚本:

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "police/crimerequest.aspx/request",
        dataType: "json",
        // success: insertCallback 
        success: function (data) {
            $('#requestResult').append(data.d);
        },
        error: function () {
            alert('Sorry there was an error, try again!');
            return false;
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2021-12-31
      • 2011-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-29
      • 1970-01-01
      • 2017-03-02
      相关资源
      最近更新 更多