提供身份验证以使用HTTPwebrequest连接到Web服务器 [英] Providing authentication to connect to web server using HTTPwebrequest
本文介绍了提供身份验证以使用HTTPwebrequest连接到Web服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
namespace ishant
{
class WebFetch
{
static void Main(string[] args)
{
// used to build entire input
StringBuilder sb = new StringBuilder();
// used on each read operation
byte[] buf = new byte[8192];
// prepare the web page we will be asking for
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create("http://www.google.com");
//GETTING ERROR CODE 407!
// execute the request
HttpWebResponse response = (HttpWebResponse)
request.GetResponse();
// we will read data via the response stream
Stream resStream = response.GetResponseStream();
string tempString = null;
int count = 0;
do
{
// fill the buffer with data
count = resStream.Read(buf, 0, buf.Length);
// make sure we read some data
if (count != 0)
{
// translate from bytes to ASCII text
tempString = Encoding.ASCII.GetString(buf, 0, count);
// continue building the string
sb.Append(tempString);
}
}
while (count > 0); // any more data to read?
// print out page source
Console.WriteLine(sb.ToString());
}
}
}
推荐答案
需要代理身份验证,因此请获取您使用的默认IE设置并将其分配给您的WebRequest
Proxy authentication required, so get the default IE settings you use and assign them to your WebRequest
IWebProxy proxy = HttpWebRequest.DefaultWebProxy;
proxy.Credentials = CredentialCache.DefaultCredentials;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.google.com");
request.Proxy = proxy;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
*编辑*
如果您没有将运行代码的计算机上的默认凭据,那么您将需要提供一些自定义凭据
例如
* edit *
If you don''t have default credentials on the machine that will be running the code, then you will need to supply some custom credentials
e.g
IWebProxy proxy = HttpWebRequest.DefaultWebProxy;
NetworkCredential credentials = new NetworkCredential("UserName", "Password");
proxy.Credentials = credentials;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.google.com");
request.Proxy = proxy;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
这篇关于提供身份验证以使用HTTPwebrequest连接到Web服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文