WebClient和HttpWebRequest(401)未经授权

编程入门 行业动态 更新时间:2024-10-27 03:39:33
本文介绍了WebClient和HttpWebRequest(401)未经授权的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

YO

当我使用method =" POST";

$时,我得到(401)未经授权

b $ b

但是当我使用method =" PUT";

时它可以工作,但是asd.php无法使用

下面的代码我尝试了两种不同的方式

使用系统; 使用 System.Collections.Generic; 使用 System.Linq; 使用 System.Text; 使用 System.IO; 使用 System.Net; 使用 System.Security.Cryptography.X509Certificates; 使用 System.Net.Security; 使用 System.Net.Sockets; 使用 System.Reflection; 使用 System.Collections.Specialized; namespace SendFilesToServer { class 程序 { static void Main(字符串 [] args) { 尝试 { doWebClientStuff( ); } catch (例外e) { StreamWriter sw = new StreamWriter(File.OpenWrite(filePath)); sw.Write(e.ToString()); sw.Close(); } } static public void doWebClientStuff() { MyWebClient client = new MyWebClient() ; string [] files = Directory.GetFiles(" files" ); SetBypassSslCertificateValidation(); client.UseDefaultCredentials = false ; client.Credentials = new NetworkCredential(" name" ,"通过" ); string authInfo = " name:pass" ; authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo)); client.Headers [" Authorization" ] = " Basic" + authInfo; string url = " https://ip/asd.php" ; CookieContainer cookies = new CookieContainer(); NameValueCollection querystring = new NameValueCollection(); querystring [" uname" ] = " name" ; querystring [" passwd" ] = " pass" ; string text = "" ; byte [] bytes = new 字节 [0]; foreach ( string uploadfile in 文件) { // bytes = client.UploadFile(url,uploadfile); text = UploadFileEx (uploadfile,url," uploadedfile" ," application / octet-stream" ,querystring,cookies); break ; } StreamWriter sw = new StreamWriter(File.OpenWrite(filePath2)); // sw.Write(Encoding.ASCII.GetString(bytes)); sw.Write(text); sw.Close(); client.Dispose(); } / *跳过认证* / public static void SetBypassSslCertificateValidation() { ServicePointManager。 ServerCertificateValidationCallback + = new RemoteCertificateValidationCallback(BypassSslCertificateValidation); } private static bool BypassSslCertificateValidation( object sender,X509Certificate cert,X509Chain chain,SslPolicyErrors error) { return true ; } / *不是我的* / public static string UploadFileEx( string uploadfile, string url, string fileFormName, string contenttype,NameValueCollection querystring, CookieContainer cookies) { if ( (fileFormName == null )|| (fileFormName.Length == 0)) { fileFormName = "文件" ; } if ((contenttype == null )|| (contenttype.Length == 0)) { contenttype = " application / octet-stream" ; } string postdata; postdata = "?" ; if (querystring!= null ) { foreach ( string key in querystring.Keys) { postdata + = key + " =" + querystring.Get(key)+ "&安培;" ; } } Uri uri = new Uri(url + postdata); string boundary = " ------ ----" + DateTime.Now.Ticks.ToString(" x" ); HttpWebRequest webrequest =(HttpWebRequest)WebRequest.Create(uri); webrequest.CookieContainer = cookies; webrequest.ContentType = " multipart / form-data; boundary =" + boundary; webrequest.Method = " POST" ; //构建帖子消息标题 StringBuilder sb = new StringBuilder(); sb.Append(" - " ); sb.Append(boundary); sb.Append(" \\\\ nn" ); sb.Append(" Content-Disposition:form-data; name = \"" ); sb.Append(fileFormName); sb.Append(" \" ;; filename = \"" ); sb.Append(Path.GetFileName(uploadfile)); sb.Append(" \"" ); sb.Append(" \\\\ nn" ); sb.Append(" Content-Type:" ); sb.Append(contenttype); sb.Append(" \\\\ nn" ); sb.Append(" \\\\ nn" ); string postHeader = sb.ToString(); byte [] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader); //将尾随边界字符串构建为字节数组 //确保边界单独出现在一条线上 byte [] boundaryBytes = Encoding.ASCII.GetBytes(" \\\\ n - " + boundary + " ; \r\\\" ); FileStream fileStream = new FileStream(uploadfile, FileMode.Open,FileAccess.Read); long length = postHeaderBytes.Length + fileStream.Length + boundaryBytes.Length; webrequest.ContentLength = length; 流requestStream = webrequest.GetRequestStream(); //写出我们的帖子标题 requestStream.Write(postHeaderBytes,0,postHeaderBytes.Length) ; //写出文件内容 byte [] buffer = new 字节[已检查(( uint )Math.Min(4096,( int )fileStream.Length))]; int bytesRead = 0; while ((bytesRead = fileStream.Read(buffer,0,buffer.Length))!= 0) requestStream.Write(buffer ,0,bytesRead); //写出尾随边界 requestStream.Write(boundaryBytes,0,boundaryBytes.Length) ; WebResponse responce = webrequest.GetResponse(); Stream s = responce.GetResponseStream(); StreamReader sr = new StreamReader(s); return sr.ReadToEnd(); } } class MyWebClient:WebClient { protected 覆盖 WebRequest GetWebRequest(Uri地址) { HttpWebRequest request =(HttpWebRequest) base .GetWebRequest(address); request.ClientCertificates.Add( new X509Certificate(" certificate.crt" )); 返回请求; } public WebRequest asd(Uri addr) { return this .GetWebRequest(addr); } } }

解决方案

这是事实,我建议访问以下链接:

support.microsoft/kb/907273

扩展代码 原因 描述
401.1 登录失败 网络服务器会将此声明为"HTTP错误401.1 - 未经授权:由于凭据无效而拒绝访问"和"b
401.2 由于服务器配置登录失败 您的Web浏览器和IIS服务器无法就身份验证协议达成一致。 Web服务器将此声明为"HTTP错误401.2 - 未经授权:由于服务器配置而拒绝访问。"
401.3 由于资源上的ACL而未经授权 服务器可以对您进行身份验证,但您没有足够的权限来访问所请求的内容。 Web服务器将宣布此为"HTTP错误401.3 - 未经授权:由于在请求的资源上设置了ACL,访问被拒绝。”

另请参阅 使用Process Monitor排除HTTP 401.3错误

401.4 过滤器授权失败
401.5 ISAPI / CGI申请失败授权

YO

I get (401) Unauthorized

when i use method = "POST";

but when i use method = "PUT";

it works, but asd.php cant use that

in the code below i have tried 2 different ways

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Net.Security; using System.Net.Sockets; using System.Reflection; using System.Collections.Specialized; namespace SendFilesToServer { class Program { static void Main(string[] args) { try { doWebClientStuff(); } catch (Exception e) { StreamWriter sw = new StreamWriter(File.OpenWrite(filePath)); sw.Write(e.ToString()); sw.Close(); } } static public void doWebClientStuff() { MyWebClient client = new MyWebClient(); string[] files = Directory.GetFiles("files"); SetBypassSslCertificateValidation(); client.UseDefaultCredentials = false; client.Credentials = new NetworkCredential("name", "pass"); string authInfo = "name:pass"; authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo)); client.Headers["Authorization"] = "Basic " + authInfo; string url = "ip/asd.php"; CookieContainer cookies = new CookieContainer(); NameValueCollection querystring = new NameValueCollection(); querystring["uname"] = "name"; querystring["passwd"] = "pass"; string text = ""; byte[] bytes = new byte[0]; foreach (string uploadfile in files) { //bytes = client.UploadFile(url, uploadfile); text = UploadFileEx(uploadfile, url, "uploadedfile", "application/octet-stream", querystring, cookies); break; } StreamWriter sw = new StreamWriter(File.OpenWrite(filePath2)); //sw.Write(Encoding.ASCII.GetString(bytes)); sw.Write(text); sw.Close(); client.Dispose(); } /*skip certification*/ public static void SetBypassSslCertificateValidation() { ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(BypassSslCertificateValidation); } private static bool BypassSslCertificateValidation(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error) { return true; } /*Not mine*/ public static string UploadFileEx(string uploadfile, string url, string fileFormName, string contenttype, NameValueCollection querystring, CookieContainer cookies) { if ((fileFormName == null) || (fileFormName.Length == 0)) { fileFormName = "file"; } if ((contenttype == null) || (contenttype.Length == 0)) { contenttype = "application/octet-stream"; } string postdata; postdata = "?"; if (querystring != null) { foreach (string key in querystring.Keys) { postdata += key + "=" + querystring.Get(key) + "&"; } } Uri uri = new Uri(url + postdata); string boundary = "----------" + DateTime.Now.Ticks.ToString("x"); HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(uri); webrequest.CookieContainer = cookies; webrequest.ContentType = "multipart/form-data; boundary=" + boundary; webrequest.Method = "POST"; // Build up the post message header StringBuilder sb = new StringBuilder(); sb.Append("--"); sb.Append(boundary); sb.Append("\r\n"); sb.Append("Content-Disposition: form-data; name=\""); sb.Append(fileFormName); sb.Append("\"; filename=\""); sb.Append(Path.GetFileName(uploadfile)); sb.Append("\""); sb.Append("\r\n"); sb.Append("Content-Type: "); sb.Append(contenttype); sb.Append("\r\n"); sb.Append("\r\n"); string postHeader = sb.ToString(); byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader); // Build the trailing boundary string as a byte array // ensuring the boundary appears on a line by itself byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n"); FileStream fileStream = new FileStream(uploadfile, FileMode.Open, FileAccess.Read); long length = postHeaderBytes.Length + fileStream.Length + boundaryBytes.Length; webrequest.ContentLength = length; Stream requestStream = webrequest.GetRequestStream(); // Write out our post header requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length); // Write out the file contents byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)fileStream.Length))]; int bytesRead = 0; while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) requestStream.Write(buffer, 0, bytesRead); // Write out the trailing boundary requestStream.Write(boundaryBytes, 0, boundaryBytes.Length); WebResponse responce = webrequest.GetResponse(); Stream s = responce.GetResponseStream(); StreamReader sr = new StreamReader(s); return sr.ReadToEnd(); } } class MyWebClient : WebClient { protected override WebRequest GetWebRequest(Uri address) { HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address); request.ClientCertificates.Add(new X509Certificate("certificate.crt")); return request; } public WebRequest asd(Uri addr) { return this.GetWebRequest(addr); } } }

解决方案

Hi

This are the fact, I would suggest to visit the link below:

support.microsoft/kb/907273

Extended code Reason Description
401.1 Logon failed The web server will announce this as “HTTP Error 401.1 - Unauthorized: Access is denied due to invalid credentials”
401.2 Logon failed due to server configuration Your web browser and the IIS server could not agree on an authentication protocol The web server will announce this as “HTTP Error 401.2 - Unauthorized: Access is denied due to server configuration.”
401.3 Unauthorized due to ACL on resource The server could authenticate you, but you do not have sufficient permission to access the content requested. The web server will announce this as “HTTP Error 401.3 - Unauthorized: Access is denied due to an ACL set on the requested resource.”

See also Troubleshooting HTTP 401.3 errors with Process Monitor

401.4 Authorization failed by filter
401.5 Authorization failed by ISAPI/CGI application

更多推荐

WebClient和HttpWebRequest(401)未经授权

本文发布于:2023-11-09 22:41:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1573630.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:未经授权   WebClient   HttpWebRequest

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!