Bu C# ile restful web servis için yazılmıştır. Öncelikle herhangi bir rest web servisten token alma metoduna bakalım :
private static async Task<string> GetTokenAccess()
{
//istek yapacağımız web servisin token alma metod adı ve base url bilgisi eklenmelidir.
string Url = BaseUrl + "/metod_adı";
string accessToken = "";
HttpResponseMessage response;
using (HttpClient client = new HttpClient())
{
var values = new Dictionary<string, string>
{
{ "state", ConfigurationManager.AppSettings["state"].ToString() },
{ "grant_type", ConfigurationManager.AppSettings["grant_type"].ToString() },
{ "scope", ConfigurationManager.AppSettings["scope"].ToString() },
{ "username", ConfigurationManager.AppSettings["username"].ToString() },
{ "password", ConfigurationManager.AppSettings["password"].ToString() },
{ "client_id", ConfigurationManager.AppSettings["client_id"].ToString()},
{ "client_secret", ConfigurationManager.AppSettings["client_secret"].ToString()},
};
//encode işlemi yapılıyor.
var content = new FormUrlEncodedContent(values);
response = client.PostAsync(Url, content).Result;
}
// eğer responce olarak 200 kodunu dönerse buraya girecek.
if (response.StatusCode == HttpStatusCode.OK)
{
string responseBody = await response.Content.ReadAsStringAsync();
JObject resJson = JObject.Parse(responseBody);
accessToken = resJson["access_token"].ToString();
// token geçerlilik süresi ne kadarsa ona göre yazılmalıdır.
DateTime TokenBas = DateTime.Now; ;
DateTime TokenBitis = DateTime.Now.AddHours(1);
TokenRepository tokenRepository = new TokenRepository();
tokenRepository.InsertTokenData(resJson, TokenBas, TokenBitis);
counterTokenAccess = 0;
}
else
{
throw new Exception("token alma işlemi başarısız oldu");
}
return accessToken; //token değerini aldık.
}
Aldığımız token değeri ile veri gönderimi yapacağımız metod şu şekildedir :
public Response VeriGönder(ref string token, Data data)
{
//istek yapacağımız web servisin göndereceğimiz verileri alacağı metod ismi ve base url bilgisi eklenmelidir.
string url = BaseUrl + "/metod_adı";
Response res = null;
HttpResponseMessage response;
try
{
using (HttpClient client = new HttpClient())
{
var ref_values = new Dictionary<string, string>
{
{ //Data içindeki gönderilecek veriler buraya eklenir.}
};
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",token);
var contentreq = new StringContent(JsonConvert.SerializeObject(ref_values), Encoding.UTF8, "application/json");
//gönderdiğimiz web servisten dönen cevabı almak için:
response = client.PostAsync(url, contentreq).Result;
}
//bize json formatında gönderilen response değerini Data nesnesine dönüştürmek için:
string contentres = response.Content.ReadAsStringAsync().Result;
res = JsonConvert.DeserializeObject<Data>(contentres);
}