Asp.net 使用HTTP身份验证调用RESTAPI
我必须安全地调用Asp.net 使用HTTP身份验证调用RESTAPI,asp.net,.net,api,rest,c#-4.0,Asp.net,.net,Api,Rest,C# 4.0,我必须安全地调用restapi。我有一个authenticate API,它返回一个令牌。我需要将这个令牌添加到我正在调用的API中 这是我所知道的调用restapi的常用方法。我需要将字符串标记附加到此请求 // *** Establish the request string token= getAuthenticate(username,password,out token ); HttpWebRequest request = (Http
restapi
。我有一个authenticate API
,它返回一个令牌。我需要将这个令牌添加到我正在调用的API中
这是我所知道的调用restapi
的常用方法。我需要将字符串标记附加到此请求
// *** Establish the request
string token= getAuthenticate(username,password,out token );
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(lcUrl);
// *** Retrieve request info headers
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader loResponseStream = new StreamReader(response.GetResponseStream());
string lcHtml = loResponseStream.ReadToEnd();
response.Close();
loResponseStream.Close();
不知道有什么问题。。。要从Rest Uri获取响应,可以执行以下操作:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(yourUrl + token); // Append Here
request.Method = "GET"; // GET or POST Define Here
//http.Accept = "application/json"; // Add if require
//http.ContentType = "application/json"; // Add if require
String test = String.Empty;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
test = reader.ReadToEnd();
reader.Close();
dataStream.Close();
}
或
您可以通过网络客户端使用简单请求
:
例如:
WebClient webClient = new WebClient();
string json = string.Empty;
// Downloads JSon String
json = webClient.DownloadString("http://api.openweathermap.org/data/2.5/weather?q=London,uk"); // Replace your URL + Token...
还有第三方组件可用=
RestSharp
我使用的是HttpClient
,没有任何不同。我觉得这样更干净:
你面临的问题是什么?有错误吗?你的问题不清楚。。。
var uri = "http://example.com";
using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token_you_want_to_used);
var response = await httpClient.GetAsync(uri);
string result = await response.Content.ReadAsStringAsync();
}