微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用LibCurlNet从json rest API发出经过身份验证的http get请求

如何解决使用LibCurlNet从json rest API发出经过身份验证的http get请求

|| cURL请求,webrequest或任何使用方式: 因为我从未在asp.net上使用cURL,所以小黄鸟在我的头上飞来飞去。我想要达到的目标(希望也是明智的)是使用LibCurlNet dll,以便使用我给定的用户名和密码向Police API进行简单的获取请求。 使用此请求,每个请求都必须包含您的API用户名和密码。卷曲示例:
curl -u username:password http://policeapi2.rkh.co.uk/api/forces
该API使用HTTP GET请求作为标准的JSON REST Web服务实现。 我希望有一个像webmethod这样的c#类,以便使用jquery进行ajax调用以从API检索信息。 我知道如何制作网络方法,但是我不知道如何将其与LibCurlNet结合使用。 我对LibCurlNet感到困惑的唯一原因不是我爱上它,因此,如果您认为我应该使用其他方法来使用此API中的数据,请这样做。 请让我知道是否可以提供任何更清晰的信息。 非常感谢你     

解决方法

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。