本文整理汇总了C#中System.Net.CredentialCache类的典型用法代码示例。如果您正苦于以下问题:C# CredentialCache类的具体用法?C# CredentialCache怎么用?C# CredentialCache使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
CredentialCache类属于System.Net命名空间,在下文中一共展示了CredentialCache类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetFileFromSite
/// <summary>
/// method to download the contents of a file from a remote URI
/// </summary>
/// <param name="ftpUri"></param>
/// <param name="user"></param>
/// <param name="pass"></param>
/// <returns></returns>
public static string GetFileFromSite(Uri ftpUri, string user, string pass)
{
string fileString = string.Empty;
// The serverUri parameter should start with the ftp:// scheme.
if (ftpUri.Scheme != Uri.UriSchemeFtp)
{
return string.Empty;
}
// Get the object used to communicate with the server.
WebClient request = new WebClient();
// This example assumes the FTP site uses anonymous logon.
NetworkCredential nc = new NetworkCredential(user, pass);
CredentialCache cc = new CredentialCache();
cc.Add(ftpUri, "Basic", nc);
request.Credentials = cc;
try
{
byte[] newFileData = request.DownloadData(ftpUri.ToString());
fileString = System.Text.Encoding.UTF8.GetString(newFileData);
}
catch (WebException e)
{
m_logger.WriteToLogFile("FtpUtils::GetFileFromSite();ECaught: " + e.Message);
}
return fileString;
}
示例2: reset
/// <summary>
/// 重启路由
/// </summary>
private string reset(string url, string userName, string password, string method, string data)
{
CookieContainer container = new CookieContainer();
string requestUriString = url;
if (method == "GET") requestUriString += "?" + data;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUriString);
request.Method = method;
if (method == "POST") {
byte[] POSTData = new UTF8Encoding().GetBytes(data);
request.ContentLength = POSTData.Length;
request.GetRequestStream().Write(POSTData, 0, POSTData.Length);
}
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0;CIBA)";
request.CookieContainer = container;
request.KeepAlive = true;
request.Accept = "*/*";
request.Timeout = 3000;
request.PreAuthenticate = true;
CredentialCache cache = new CredentialCache();
cache.Add(new Uri(requestUriString), "Basic", new NetworkCredential(routeInfo.UserName, routeInfo.RPassword));
request.Credentials = cache;
try {
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
response.Cookies = container.GetCookies(request.RequestUri);
new StreamReader(response.GetResponseStream(), Encoding.Default).Close();
response.Close();
return string.Empty;
} catch (Exception ex) {
return ex.Message;
}
}
示例3: GatewayWebRequester
/// <summary>
/// Initializes a new instance of the <see cref="GatewayWebRequester"/> class.
/// </summary>
/// <param name="credentials">The credentials.</param>
/// <param name="contentType">Type of the content.</param>
public GatewayWebRequester(ClusterCredentials credentials, string contentType = "application/x-google-protobuf")
{
_credentials = credentials;
_contentType = contentType;
_credentialCache = new CredentialCache();
InitCache();
}
示例4: GoogleAuthManagerExample
public static string GoogleAuthManagerExample( string uri, string username, string password )
{
AuthenticationManager.Register( new GoogleLoginClient() );
// Now 'GoogleLogin' is a recognized authentication scheme
GoogleCredentials creds = new GoogleCredentials( username, password, "HOSTED_OR_GOOGLE" );
// Cached credentials can only be used when requested by specific URLs and authorization schemes
CredentialCache credCache = new CredentialCache();
credCache.Add( new Uri( uri ), "GoogleLogin", creds );
WebRequest request = WebRequest.Create( uri );
// Must be a cache, basic credentials are cleared on redirect
request.Credentials = credCache;
request.PreAuthenticate = true; // More efficient, but optional
// Process response
var response = request.GetResponse() as HttpWebResponse;
var stream = new StreamReader( response.GetResponseStream(), Encoding.Default );
var responseString = stream.ReadToEnd();
stream.Close();
// Erase cached auth token unless you'll use it again soon.
creds.PrevAuth = null;
return responseString;
}
示例5: CallServiceGet
/// <summary>
/// Method used for making an http GET call
/// </summary>
/// <param name="credentialsDetails">An object that encapsulates the Constant Contact credentials</param>
/// <param name="contactURI">The URL for the call</param>
/// <param name="strRequest">The request string representation</param>
/// <param name="strResponse">The response string representation</param>
/// <returns>The string representation of the response</returns>
public static string CallServiceGet(CredentialsDetails credentialsDetails, string contactURI,
out string strRequest, out string strResponse)
{
var loginCredentials = new CredentialCache
{
{
new Uri("https://api.constantcontact.com/ws/customers/" +
credentialsDetails.User),
"Basic",
new NetworkCredential(
credentialsDetails.Key + "%" + credentialsDetails.User,
credentialsDetails.Password)
}
};
var request = WebRequest.Create(contactURI);
request.Credentials = loginCredentials;
var response = (HttpWebResponse) request.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
var xmlResponse = reader.ReadToEnd();
reader.Close();
response.Close();
strRequest = PrintRequestString(request, credentialsDetails, string.Empty);
strResponse = xmlResponse;
return xmlResponse;
}
示例6: Get
/// <summary>
/// <para>Issue an HTTP GET request to the given <paramref name="requestUrl"/>.</para>
/// <para>The <paramref name="requestUrl"/> can contain query parameters
/// (name=value pairs).</para>
/// </summary>
/// <param name="requestUrl">The URL to issue the GET request to (with optional query
/// parameters)</param>
/// <returns>The server response.</returns>
/// <exception cref="HttpUtilsException">If an error issuing the GET request or parsing
/// the server response occurs.</exception>
public string Get(String requestUrl)
{
try
{
Uri requestUri = new Uri(requestUrl);
HttpWebRequest apiRequest = WebRequest.Create(requestUri) as HttpWebRequest;
apiRequest.Method = "GET";
apiRequest.KeepAlive = false;
if (username != null && password != null)
{
CredentialCache authCredentials = new CredentialCache();
authCredentials.Add(requestUri, "Basic", new NetworkCredential(username, password));
apiRequest.Credentials = authCredentials;
}
// Get response
string apiResponse = "";
using (HttpWebResponse response = apiRequest.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
apiResponse = reader.ReadToEnd();
}
return apiResponse;
}
catch (Exception e)
{
if (log.IsErrorEnabled)
log.Error("Get failed", e);
throw new HttpUtilsException("Get failed", e);
}
}
示例7: GetOptions
// This function sends the OPTIONS request and returns an
// ASOptionsResponse class that represents the response.
public ASOptionsResponse GetOptions()
{
if (credential == null || server == null)
throw new InvalidDataException("ASOptionsRequest not initialized.");
string uriString = string.Format("{0}//{1}/Microsoft-Server-ActiveSync", UseSSL ? "https:" : "http:", Server);
Uri serverUri = new Uri(uriString);
CredentialCache creds = new CredentialCache();
// Using Basic authentication
creds.Add(serverUri, "Basic", Credentials);
HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(uriString);
httpReq.Credentials = creds;
httpReq.Method = "OPTIONS";
try
{
HttpWebResponse httpResp = (HttpWebResponse)httpReq.GetResponse();
ASOptionsResponse response = new ASOptionsResponse(httpResp);
httpResp.Close();
return response;
}
catch (Exception ex)
{
ASError.ReportException(ex);
return null;
}
}
示例8: HttpService
/// <summary>
/// Constructor
/// </summary>
/// <param name="authManager">The authorization manager to use.</param>
/// <param name="connectionInfo">Connection Information</param>
internal HttpService(ApiAuthManager authManager, ConnectionInfo connectionInfo)
{
if (authManager == null)
throw new ArgumentNullException("authManager");
if (connectionInfo == null)
throw new ArgumentNullException("connectionInfo");
this.authManager = authManager;
this.connectionInfo = connectionInfo;
if (connectionInfo.AuthType == AuthorizationType.Basic)
{
Server = connectionInfo.Server;
credentials = new CredentialCache { { connectionInfo.Server, "Basic", new NetworkCredential(connectionInfo.UserName, connectionInfo.Password) } };
}
else if (connectionInfo.AuthType == AuthorizationType.ZSessionID)
{
Server = connectionInfo.Server;
credentials = null;
}
else if (connectionInfo.AuthType == AuthorizationType.ApiKey)
{
Server = connectionInfo.Server;
credentials = new CredentialCache { { connectionInfo.Server, "Basic", new NetworkCredential(connectionInfo.ApiKey, connectionInfo.ApiKey) } };
}
}
示例9: multiple_credentials_via_user_supplied_credential_cache
public void multiple_credentials_via_user_supplied_credential_cache()
{
var cred = new OAuth2Client.OAuth2Credential(
"apiv1",
new OAuth2Client.Storage.JsonFileStorage(
@"C:\Projects\github\oauth2_files\local_versiononeweb_client_secrets.json",
@"C:\Projects\github\oauth2_files\local_versiononeweb_creds.json"),
null
);
var cache = new CredentialCache();
var simpleCred = new NetworkCredential(V1Username, V1Password);
cache.Add(V1Uri, "Basic", simpleCred);
cache.Add(V1Uri, "Bearer", cred);
var windowsIntegratedCredential = CredentialCache.DefaultNetworkCredentials;
// TODO explore: CredentialCache.DefaultCredentials
// Suppose for some weird reason you just wanted to support NTLM:
cache.Add(V1Uri, "NTLM", windowsIntegratedCredential);
var connector = new VersionOneAPIConnector(V1Path, cache);
connector.HttpGet("rest-1.v1/Data/Member/20");
}
示例10: TestLookupCredentialWithCredentialCache
public void TestLookupCredentialWithCredentialCache()
{
var credentials = new CredentialCache();
var credPopuser1 = new NetworkCredential("popuser1", "password");
var credPopuser2 = new NetworkCredential("popuser2", "password");
var credImapuser1 = new NetworkCredential("imapuser1", "password");
var credImapuser2 = new NetworkCredential("imapuser2", "password");
credentials.Add("localhost", 110, string.Empty, credPopuser1);
credentials.Add("localhost", 110, "cram-md5", credPopuser2);
credentials.Add("localhost", 143, string.Empty, credImapuser1);
credentials.Add("localhost", 143, "digest-md5", credImapuser2);
Assert.AreEqual(credPopuser1, credentials.LookupCredential("localhost", 110, "popuser1", null));
Assert.AreEqual(credPopuser2, credentials.LookupCredential("localhost", 110, "popuser2", "CRAM-MD5"));
Assert.AreEqual(credImapuser1, credentials.LookupCredential("localhost", 143, "imapuser1", null));
Assert.AreEqual(credImapuser2, credentials.LookupCredential("localhost", 143, "imapuser2", "DIGEST-MD5"));
Assert.AreEqual(credPopuser1, credentials.LookupCredential("localhost", 110, null, null));
Assert.AreEqual(credPopuser2, credentials.LookupCredential("localhost", 110, null, "CRAM-MD5"));
Assert.IsNull(credentials.LookupCredential("localhost", 110, null, "DIGEST-MD5"));
Assert.AreEqual(credImapuser1, credentials.LookupCredential("localhost", 143, null, null));
Assert.AreEqual(credImapuser2, credentials.LookupCredential("localhost", 143, null, "DIGEST-MD5"));
Assert.IsNull(credentials.LookupCredential("localhost", 143, null, "CRAM-MD5"));
}
示例11: CustomerGetAll
public ActionResult CustomerGetAll()
{
var requestUri = new Uri("http://localhost:44354//v1/Customers");
var credCache = new CredentialCache
{
{
requestUri,
"Basic",// "Digest",
new NetworkCredential("Test", "Test_123", "localhost")
}
};
using (var clientHander = new HttpClientHandler
{
Credentials = credCache,
PreAuthenticate = true
})
using (var httpClient = new HttpClient(clientHander))
{
for (var i = 0; i < 5; i++)
{
var responseTask = httpClient.GetAsync(requestUri);
var bb = responseTask.Result.Content.ReadAsStringAsync();
responseTask.Result.EnsureSuccessStatusCode();
}
}
return Json("");
}
示例12: Main
static void Main(string[] args)
{
string strBaseUrl = "http://192.168.1.1";
string strUrl = strBaseUrl + "/userRpm/SysRebootRpm.htm?Reboot={0}";//%D6%D8%C6%F4%C2%B7%D3%C9%C6%F7";
string strCommand = "重启路由器";
strCommand = HttpUtility.UrlEncode(strCommand, Encoding.GetEncoding("GB2312"));
strUrl = string.Format(strUrl, strCommand);
NetworkCredential myCred = new NetworkCredential(
"1802", "1qaz2wsx",null);
CredentialCache myCache = new CredentialCache();
myCache.Add(new Uri(strBaseUrl), "Basic", myCred);
//myCache.Add(new Uri("app.contoso.com"), "Basic", myCred);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strUrl);
request.Credentials = myCache;
try
{
WebResponse response = request.GetResponse();
}
catch (Exception)
{
throw;
}
//string strIPCtlFormat = "QoSCtrl={0}&h_lineType={1}&h_down_bandWidth={2}";
//string strFormFormat = "QoSCtrl={0}&h_lineType={1}&h_down_bandWidth=4000&hips_1=1&hipe_1=2&hm_1=0&hbW_1=999&hn_1=hahaha&hen_1=1&hips_2=&hipe_2=&hm_2=0&hbW_2=&hn_2=&hen_2=&hips_3=&hipe_3=&hm_3=0&hbW_3=&hn_3=&hen_3=&hips_4=&hipe_4=&hm_4=0&hbW_4=&hn_4=&hen_4=&hips_5=&hipe_5=&hm_5=0&hbW_5=&hn_5=&hen_5=&hips_6=&hipe_6=&hm_6=0&hbW_6=&hn_6=&hen_6=&hips_7=&hipe_7=&hm_7=0&hbW_7=&hn_7=&hen_7=&hips_8=&hipe_8=&hm_8=0&hbW_8=&hn_8=&hen_8=&sv=%B1%A3%20%B4%E6"
}
示例13: CreateClientHandler
public static HttpClientHandler CreateClientHandler(string serviceUrl, ICredentials credentials)
{
if (serviceUrl == null)
{
throw new ArgumentNullException("serviceUrl");
}
// Set up our own HttpClientHandler and configure it
HttpClientHandler clientHandler = new HttpClientHandler();
if (credentials != null)
{
// Set up credentials cache which will handle basic authentication
CredentialCache credentialCache = new CredentialCache();
// Get base address without terminating slash
string credentialAddress = new Uri(serviceUrl).GetLeftPart(UriPartial.Authority).TrimEnd(uriPathSeparator);
// Add credentials to cache and associate with handler
NetworkCredential networkCredentials = credentials.GetCredential(new Uri(credentialAddress), "Basic");
credentialCache.Add(new Uri(credentialAddress), "Basic", networkCredentials);
clientHandler.Credentials = credentialCache;
clientHandler.PreAuthenticate = true;
}
// Our handler is ready
return clientHandler;
}
示例14: DigestCredentials
public void DigestCredentials()
{
var requestUri = new Uri("http://localhost/DigestAuthDemo/");
var credCache = new CredentialCache
{
{
new Uri("http://localhost/"),
"Digest",
new NetworkCredential("Test", "Test", "/")
}
};
using (var clientHander = new HttpClientHandler
{
Credentials = credCache,
PreAuthenticate = true
})
using (var httpClient = new HttpClient(clientHander))
{
for (var i = 0; i < 5; i++)
{
var responseTask = httpClient.GetAsync(requestUri);
responseTask.Result.EnsureSuccessStatusCode();
}
}
}
示例15: GetCredential
// Authentication using a Credential Cache to store the authentication
CredentialCache GetCredential(string uri, string username, string password)
{
// ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
var credentialCache = new CredentialCache();
credentialCache.Add(new System.Uri(uri), "Basic", new NetworkCredential(username, password));
return credentialCache;
}