简体   繁体   中英

C# - Consuming REST web service over https

What's the best way to consume secure REST web service in C#? Web Service username and password are supplied in URL...

Several options:

HttpWebRequest class. Powerful but sometimes complex to use.

WebClient class. Less features, but should work for simpler web services, and much simpler.

The new HttpClient in the WCF REST Starter Kit. (The Starter Kit is a separate download, not a part of the .NET Framework).

Use WebRequest class to make the request and HttpWebResponse to get the response.

I used following code for consuming webservice.My user name,password and Url are saved in variables UserName,Pwd and Url respectively.

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 .

I hope the password in the URL is somwhow encrypted :). Maybe this will help you:

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.

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. You have full access to Http status codes, and Http Headers.

What more can you ask for?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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