65.9K
CodeProject 正在变化。 阅读更多。
Home

通过代理服务器连接到 Web 服务

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.88/5 (23投票s)

2003 年 6 月 30 日

2分钟阅读

viewsIcon

732754

downloadIcon

1

通过代理服务器连接到 Web 服务

引言

本文档解释了如何通过代理服务器访问 Web 服务。

使用代码

为了演示这个例子,我们将使用 Google 提供的公共 Web 服务。要使用此 Web 服务,我们需要从 Google 获取验证密钥。接下来,我们定义了搜索条件并显示获取到的记录总数。

我们使用了以下库:

NetworkCredential

为基于密码的身份验证方案(如基本身份验证、摘要身份验证、NTLM 和 Kerberos 身份验证)提供凭据。有关此类型所有成员的列表,请参阅 NetworkCredential 成员。NetworkCredential 类是一个基类,它在基于密码的身份验证方案(如基本身份验证、摘要身份验证、NTLM 和 Kerberos 身份验证)中提供凭据。实现 ICredentials 接口的类(如 CredentialCache 类)会返回 NetworkCredential 实例。此类不支持基于公钥的身份验证方法,如 SSL 客户端身份验证。

WebProxy

包含 WebRequest 类的 HTTP 代理设置。有关此类型所有成员的列表,请参阅 WebProxy 成员。WebProxy 类包含 WebRequest 实例用于覆盖 GlobalProxySelection 中代理设置的代理设置。WebProxy 类是 IWebProxyinterface 的基本实现。

The Proxy Server IP Adress is 127,0,1,2 and the port is the 80. 
The data of the user for the authentication with the proxy are: 
User Id: user 
Password: pwd 
Domain: MyDomain 

以下 VB.NET 代码展示了一个示例:

' Search button: do a search, display number of results 
Private Sub btnSearch_Click(ByVal sender As System.Object, _
  ByVal e As System.EventArgs) Handles btnSearch.Click 

' Create a Google Search object 
Dim s As New Google.GoogleSearchService 

Try 

' google params 
Dim strLicenceseKey As String = "google license key" ' google license key 
Dim strSearchTerm As String = "Bruno Capuano" ' google license key 

' proxy settings 
Dim cr As New System.Net.NetworkCredential("user", "pwd", "MyDomain") 
Dim pr As New System.Net.WebProxy("127.0.1.2", 80) 

pr.Credentials = cr 
s.Proxy = pr 

' google search
Dim r As Google.GoogleSearchResult = s.doGoogleSearch(strLicenceseKey, _
  strSearchTerm, 0, 10, True, "", False, "", "", "")
' Extract the estimated number of results for the search and display it
Dim estResults As Integer = r.estimatedTotalResultsCount 

MsgBox(CStr(estResults))

Catch ex As System.Web.Services.Protocols.SoapException

MsgBox(ex.Message)

End Try

End Sub 

如果您想使用当前用户的凭据,可以使用 DefaultCredentials 属性。DefaultCredentials 属性仅适用于基于 NTLM、协商和 Kerberos 的身份验证。示例:

' set default credentials
pr.Credentials = System.Net.CredentialCache.DefaultCredentials 

DefaultCredentials 代表应用程序正在运行的安全上下文中系统的凭据。对于客户端应用程序,这些通常是运行该应用程序的 Windows 凭据(用户名、密码和域)。对于 ASP.NET 应用程序,默认凭据是已登录用户的凭据,或正在模拟的用户。

注意 - DefaultCredentials 返回的 ICredentials 实例无法用于查看当前安全上下文的用户名、密码或域。

结论

这是我的第一篇文章,也是一篇非常简单的文章。欢迎提出任何问题或建议!再见!

© . All rights reserved.