使用用户名和密码调用Rest API-如何 [英] Calling a rest api with username and password - how to

查看:438
本文介绍了使用用户名和密码调用Rest API-如何的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是不熟悉api并通过.NET调用它们的新手

I am new to rest api's and calling them via .NET

我有一个api: https://sub.domain.com/api/operations? param = value& param2 = value

关于api的注释说,要进行授权,我需要使用基本的访问身份验证-我该怎么做?

The notes for the api say that to authorize I need to use the basic access authentication - how do I do that?

我目前有以下代码:

        WebRequest req = WebRequest.Create(@"https://sub.domain.com/api/operations?param=value&param2=value");
        req.Method = "GET";
        //req.Credentials = new NetworkCredential("username", "password");
        HttpWebResponse resp = req.GetResponse() as HttpWebResponse;

但是我收到401未经授权的错误.

However I get a 401 unauthorized error.

我缺少什么,如何使用基本访问身份验证来形成api调用?

What am I missing, how do I form api calls using the basic access auth?

推荐答案

如果API说要使用HTTP基本身份验证,则需要在请求中添加一个Authorization标头.我会更改您的代码,使其看起来像这样:

If the API says to use HTTP Basic authentication, then you need to add an Authorization header to your request. I'd alter your code to look like this:

    WebRequest req = WebRequest.Create(@"https://sub.domain.com/api/operations?param=value&param2=value");
    req.Method = "GET";
    req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("username:password"));
    //req.Credentials = new NetworkCredential("username", "password");
    HttpWebResponse resp = req.GetResponse() as HttpWebResponse;

当然用正确的值替换"username""password".

Replacing "username" and "password" with the correct values, of course.

这篇关于使用用户名和密码调用Rest API-如何的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆