我正在用C#.Net编写一个REST客户机,使用RestSharp。有两个API调用-一个是"Auth“调用,第二个是"getKey”调用。"Auth“调用在响应中抛出一个"Auth令牌”,我希望从响应中解析该令牌,并将其作为头传递给第二个"getkey“调用。请举例说明
发布于 2018-06-29 10:33:44
我已经给出了一些例子来实现你的场景。请使用下面的例子,并根据您的要求进行修改。
RestUtils类:
添加请求标头,如果您的应用程序需要一些额外的头。
class RestUtils
{
private static readonly RestClient _restClient = new RestClient();
public static void SetBaseURL(String host)
{
_restClient.BaseUrl = new Uri(host);
}
public static string GetResponse(String endpoint, String token)
{
var request = new RestRequest(endpoint, Method.GET);
request.AddHeader("Accept", "application/json");
request.AddHeader("Authorization", token);
IRestResponse response = _restClient.Execute(request);
return response.Content;
}
public static string GetToken(String endpoint)
{
var request = new RestRequest(endpoint, Method.GET);
request.AddHeader("Accept", "application/json");
IRestResponse response = _restClient.Execute(request);
return response.Content;
}
}
TestClass:
在您的测试类中,您可以添加以下步骤,并且可以得到预期的结果。前两行将被执行,并将身份验证令牌作为输出。因此,您可以在随后的行中为其他API使用检索到的令牌。以另一种方式,您可以创建一个属性类并设置检索到的令牌值.So,从而可以从各个类访问令牌。
//Specify the Base URI of your Token Specific API
RestUtils.SetBaseURL("https://login.microsoftonline.com/");
//Specify the End Point of your Token Specific API
String token = RestUtils.GetToken("/oauth2/token");
//Specify the Base URI of your actual Test API
RestUtils.SetBaseURL("XXXXXXX");
String response = RestUtils.GetResponse(token);
https://stackoverflow.com/questions/51051943
复制