Consuming REST Service pb

2019-08-03 19:08发布

问题:

I'm having some problem consuming REST Service and want to figure out what I'm missing in implementation.

https://<server-name-or-address>/api/sessions

if I call this rest api using cURL, it works just fine by following script

curl -i -k -H "Accept:application/*+xml;version=1.5" -u username:password -X POST https://<server-name-or-address>/api/sessions

However, it isn't working at all with C# asp.net. I'm not sure what I'm missing here. Here are my attempts:

1) Using HTTP Web Request

Uri address = new Uri(url);
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
request.Method = "POST";
request.Accept = "application/*+xml;version=1.5";

request.Credentials = new NetworkCredential(username,password);

HttpWebResponse response = request.GetResponse() as HttpWebResponse;

// following exception fires on calling aforementioned statement The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

2) Using Hammock.net

Hammock.RestClient client = new Hammock.RestClient();
string encodedAPIKey = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", username, password)));
client.AddHeader("Accept", "application/*+xml;version=1.5");
client.AddHeader("Authorization", "Basic " + username + ":" + password);
client.Authority = url;
Hammock.RestRequest req = new Hammock.RestRequest();
req.Path = url;
Hammock.RestResponse response = client.Request(req);
string _result = client.Request(req).Content; // exception

3) Using RestSharp

string _loginInfo = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", username, password)));
RestSharp.RestClient client = new RestSharp.RestClient();
client.AddDefaultHeader("Accept", "application/*+xml;version=1.5");
client.AddDefaultHeader("Authorization", "Basic " + _loginInfo);
client.BaseUrl = url;
RestSharp.RestRequest request = new RestSharp.RestRequest();
request.AddUrlSegment("method", "POST");
request.AddUrlSegment("uri", url);
string result = client.Execute(request).Content;

I also have tried with HttpClient, WebRequest, WebClient though nothing appears to work.

回答1:

Try manually setting the Authorization header yourself in the HTTP request.

string credentials = String.Format("{0}:{1}", username, password);
byte[] bytes = Encoding.ASCII.GetBytes(credentials);
string base64 = Convert.ToBase64String(bytes);
string authorization = String.Concat("Basic ", base64);
request.Headers.Add("Authorization", authorization);

EDIT:

It looks as though it may be due to a self-signed, expired, or otherwise invalid cert. Try the following

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

Gleaned from this SO: https://stackoverflow.com/questions/5595049/servicepointmanager-servercertificatevalidationcallback-question