使用基本身份验证的HttpWebRequest [英] HttpWebRequest using Basic authentication

查看:271
本文介绍了使用基本身份验证的HttpWebRequest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过一个模仿基本身份验证请求"的身份验证请求,该请求是我们在为此行为设置IIS时经常看到的.

I'm trying to go through an authentication request that mimics the "basic auth request" we're used to seeing when setting up IIS for this behavior.

URL为: https://telematicoprova. agenziadogane.it/TelematicoServiziDiUtilitaWeb/ServiziDiUtilitaAutServlet?UC=22&SC=1&ST=2
(警告:https!)

The URL is: https://telematicoprova.agenziadogane.it/TelematicoServiziDiUtilitaWeb/ServiziDiUtilitaAutServlet?UC=22&SC=1&ST=2
(warning: https!)

此服务器作为应用程序服务器在UNIX和Java下运行.

This server is running under UNIX and Java as application server.

这是我用来连接到该服务器的代码:

This is the code I use to connect to this server:

CookieContainer myContainer = new CookieContainer();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://telematicoprova.agenziadogane.it/TelematicoServiziDiUtilitaWeb/ServiziDiUtilitaAutServlet?UC=22&SC=1&ST=2");
request.Credentials = new NetworkCredential(xxx,xxx);
request.CookieContainer = myContainer;
request.PreAuthenticate = true;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

(我是从本网站的另一篇文章中复制的).但是我从服务器收到以下答案:

(I copied this from another post on this site). But I receive this answer from the server:

基础连接已关闭:发生意外错误 发送.

The underlying connection was closed: An unexpected error occurred on a send.

我认为我尽了我所有的C#知识所能提供的所有可能的任务,但是没有任何事情……

I think I tried every possible task my knowledge on C# has to offer me, but nothing...

推荐答案

您也可以自己添加授权标头.

You can also just add the authorization header yourself.

只需输入名称"Authorization"和值"Basic BASE64({USERNAME:PASSWORD})"

Just make the name "Authorization" and the value "Basic BASE64({USERNAME:PASSWORD})"

String username = "abc";
String password = "123";
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
httpWebRequest.Headers.Add("Authorization", "Basic " + encoded);

编辑

每个

Edit

Switched the encoding from UTF-8 to ISO 8859-1 per What encoding should I use for HTTP Basic Authentication? and Jeroen's comment.

这篇关于使用基本身份验证的HttpWebRequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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