简体   繁体   English

C# - 通过https使用REST Web服务

[英]C# - Consuming REST web service over https

What's the best way to consume secure REST web service in C#? 在C#中使用安全REST Web服务的最佳方法是什么? Web Service username and password are supplied in URL... URL服务用户名和密码在URL中提供...

Several options: 几个选项:

HttpWebRequest class. HttpWebRequest类。 Powerful but sometimes complex to use. 功能强大但有时使用起来很复杂。

WebClient class. WebClient类。 Less features, but should work for simpler web services, and much simpler. 功能较少,但应该适用于更简单的Web服务,并且更简单。

The new HttpClient in the WCF REST Starter Kit. WCF REST入门套件中的新HttpClient。 (The Starter Kit is a separate download, not a part of the .NET Framework). (入门套件是单独下载,不是.NET Framework的一部分)。

Use WebRequest class to make the request and HttpWebResponse to get the response. 使用WebRequest类发出请求,使用HttpWebResponse获取响应。

I used following code for consuming webservice.My user name,password and Url are saved in variables UserName,Pwd and Url respectively. 我使用以下代码来使用webservice.My用户名,密码和Url分别保存在变量UserName,Pwd和Url中。

WebRequest Webrequest;
HttpWebResponse response;

Webrequest = WebRequest.Create(Url);
byte[] auth1 = Encoding.UTF8.GetBytes(UserName + ":" + Pwd);
Webrequest.Headers["Authorization"] = "Basic " + System.Convert.ToBase64String(auth1);
Webrequest.Method = "GET";
Webrequest.ContentType = "application/atom+xml";

response = (HttpWebResponse)Webrequest.GetResponse();
Stream streamResponse = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamResponse);
string Response = streamReader.ReadToEnd();

Response string will be available in variable Response . 响应字符串将在变量Response可用。

I hope the password in the URL is somwhow encrypted :). 我希望URL中的密码是somwhow加密:)。 Maybe this will help you: 也许这会对你有所帮助:

http://social.msdn.microsoft.com/forums/en-US/wcf/thread/3c8db0bf-984e-426b-b068-d80165ed1b37/ http://social.msdn.microsoft.com/forums/en-US/wcf/thread/3c8db0bf-984e-426b-b068-d80165ed1b37/

Based on the little information you provided I would say that using the HttpWebRequest class is your best option. 根据您提供的少量信息,我会说使用HttpWebRequest类是您的最佳选择。

It is relatively easy to use, there are lots of examples of how to use it and it will work with any media-type the REST interface delivers. 它相对容易使用,有很多如何使用它的例子,它可以与REST接口提供的任何媒体类型一起使用。 You have full access to Http status codes, and Http Headers. 您可以完全访问Http状态代码和Http Headers。

What more can you ask for? 你还能要求什么呢?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM