使用REST服务pb

时间:2012-06-28 19:23:18

标签: asp.net web-services api rest

我在使用REST服务时遇到了一些问题,想要弄清楚我在实现中缺少什么。

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

如果我使用cURL调用此rest api,它可以通过以下脚本

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

但是,它与C#asp.net完全不兼容。我不确定我在这里缺少什么。以下是我的尝试:

1)使用HTTP Web请求

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;

//在调用上述声明时发生异常触发 底层连接已关闭:无法为SSL / TLS安全通道建立信任关系。

2)使用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)使用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;

我也尝试过使用HttpClient,WebRequest,WebClient,但似乎没有任何工作。

1 个答案:

答案 0 :(得分:1)

尝试在HTTP请求中自行手动设置Authorization标头。

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);

编辑:

看起来好像是由于自签名,过期或无效的证书。请尝试以下

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

从此SO中收集:https://stackoverflow.com/questions/5595049/servicepointmanager-servercertificatevalidationcallback-question