C# 带有用户名和密码的 HTTP GET 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14260905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:12:46  来源:igfitidea点击:

HTTP GET Request with Username & Password

c#httpcloudconsole-application

提问by nairware

This is my first attempt at creating a console appwhich can make a HTTP GETrequest and print the response to the console.

这是我第一次尝试创建一个console app可以发出HTTP GET请求并将响应打印到console.

Thus far, the code works, but only for URIswhich do not require a username/password.

到目前为止,该代码有效,但仅适用于URIs不需要username/password.

My ultimate purpose is to use a cloud/hosting APIwhich accepts HTTP GETrequests as triggersfor taking certain actions. As such, I have to use a username/passwordfor this.

我的最终目的是使用cloud/hosting API接受HTTP GET请求作为执行某些操作的触发器。因此,我必须为此使用 a username/password

using System;
using System.Net;
using System.IO;

namespace HttpTestProject {

    class Program {

        static void Main(string[] args) {

            Uri uri = new Uri("http://www.google.com");
            string username = "asdf";
            string password = "asdf";

            NetworkCredential cred = new NetworkCredential(username, password);
            CredentialCache cache = new CredentialCache();
            cache.Add(uri, "Basic", cred);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream resStream = response.GetResponseStream();

            StreamReader reader = new StreamReader(resStream);
            string text = reader.ReadToEnd();

            Console.WriteLine(text);
            Console.ReadLine();

        }

    }

}

采纳答案by istepaniuk

If you have to add basic authentication to your request without waiting for a challenge you can append the header manually:

如果您必须在不等待质询的情况下向请求添加基本身份验证,您可以手动附加标头:

var request = WebRequest.Create("http://myserver.com/service");
string authInfo = userName + ":" + userPassword;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));

//like this:
request.Headers["Authorization"] = "Basic " + authInfo;

var response = request.GetResponse();