用Net.Http替换RestSharp GET请求



我有一个RestSharp Entitlement检查代码可以工作,但我需要用一个使用本机C#库(Net.Http(的代码来替换它。

这是我的代码:

public static bool Entitlement(string appId, string userId)
{
//REST API call for the entitlement API.
//We are using RestSharp for simplicity.
//You may choose to use another library.
//(1) Build request
var client = new RestClient();
client.BaseUrl = new System.Uri(@"https://apps.example.com/");
//Set resource/end point
var request = new RestRequest();
request.Resource = "webservices/checkentitlement";
request.Method = Method.GET;
//Add parameters
request.AddParameter("userid", userId);
request.AddParameter("appid", appId);
//(2) Execute request and get response
IRestResponse response = client.Execute(request);
//Get the entitlement status.
bool isValid = false;
if (response.StatusCode == HttpStatusCode.OK)
{
JsonDeserializer deserial = new JsonDeserializer();
EntitlementResponse entitlementResponse = deserial.Deserialize<EntitlementResponse>(response);
isValid = entitlementResponse.IsValid;
}
//
return isValid;
}

class EntitlementResponse
{
public string UserId { get; set; }
public string AppId { get; set; }
public bool IsValid { get; set; }
public string Message { get; set; }
}

尝试这个

public async Task<EntitlementResponse> Entitlement(string appId, string userId)
{
using (var client = new HttpClient())
{
var baseAddress ="https://apps.example.com/";
var api = "/webservices/checkentitlement/"+  userId.ToString()+"/" + appId.ToString();
//or since I don't know how your API looks
var api = "/webservices/checkentitlement?userId="+  userId.ToString()+"&appId=" + appId.ToString()
client.BaseAddress = new Uri(baseAddress);
var contentType = new MediaTypeWithQualityHeaderValue("application/json");
client.DefaultRequestHeaders.Accept.Add(contentType);
var response = await client.GetAsync(api);
var statusCode = response.StatusCode.ToString();
if (response.IsSuccessStatusCode)
{
var json = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<EntitlementResponse>(json);
}
}
return null;
}

相关内容

  • 没有找到相关文章

最新更新