本文整理汇总了C#中RestSharp.RestClient.ExecutePostTaskAsync方法的典型用法代码示例。如果您正苦于以下问题:C# RestClient.ExecutePostTaskAsync方法的具体用法?C# RestClient.ExecutePostTaskAsync怎么用?C# RestClient.ExecutePostTaskAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类RestSharp.RestClient
的用法示例。
在下文中一共展示了RestClient.ExecutePostTaskAsync方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: IsAuthorization
public static async Task<IRestResponse<ResultValue>> IsAuthorization(string email, string versionNumber)
{
var client = new RestClient(SystemResource.BoardServiceClient);
var request = new RestRequest(string.Format(SystemResource.IsAuthorizationRequest, email, versionNumber), Method.POST);
return await client.ExecutePostTaskAsync<ResultValue>(request);
}
示例2: CreateUser
/// <summary>
/// Create a Popcorn user account
/// </summary>
/// <param name="username">The username</param>
/// <param name="firstname">The first name</param>
/// <param name="lastname">The last name</param>
/// <param name="password">The password</param>
/// <param name="email">The email</param>
/// <param name="ct">The cancellation token</param>
/// <returns>User</returns>
public async Task<Models.Account.User> CreateUser(string username, string firstname, string lastname,
string password, string email, CancellationToken ct)
{
var watch = Stopwatch.StartNew();
var restClient = new RestClient(Constants.PopcornApiEndpoint);
var request = new RestRequest("/{segment}", Method.POST);
request.AddUrlSegment("segment", "api/accounts/create");
request.AddParameter("username", username);
request.AddParameter("firstname", firstname);
request.AddParameter("lastname", lastname);
request.AddParameter("email", email);
request.AddParameter("password", password);
request.AddParameter("confirmpassword", password);
var response = await restClient.ExecutePostTaskAsync(request, ct);
if (response.ErrorException != null)
{
throw new Exception();
}
var user =
await Task.Run(() => JsonConvert.DeserializeObject<Models.Account.User>(response.Content), ct);
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
Logger.Debug(
$"CreateUser ({username}, {firstname}, {lastname}, {password}, {email}) in {elapsedMs} milliseconds.");
return user;
}
示例3: CallFunctionAsync
// var result = Spark.RESTCore.CallFunctionAsync("brew").Result;
public static async Task<FunctionResponse> CallFunctionAsync(string functionName){
// curl https://api.spark.io/v1/devices/0123456789abcdef01234567/brew \
// -d access_token=1234123412341234123412341234123412341234 \
// -d "args=202,230"
// // EXAMPLE RESPONSE
// {
// "id": "0123456789abcdef01234567",
// "name": "prototype99",
// "connected": true,
// "return_value": 42
// }
var request = String.Format("https://api.spark.io/v1/devices/{0}/{2}?access_token={1}",Configuration.DeviceID,Configuration.AccessToken,functionName);
var client = new RestClient ();
var req = new RestRequest (request);
var response = await client.ExecutePostTaskAsync (req);
if (response.StatusCode == HttpStatusCode.OK) {
return JsonConvert.DeserializeObject<FunctionResponse>(response.Content);
}
return null;
}
示例4: GetAuthTokenIRestResponseAsync
private async Task<IRestResponse> GetAuthTokenIRestResponseAsync(AuthRequest request)
{
// create web request
var endPointWithClientInfo = BuildFqdnEndpointWithClientInfo(config.QueryString);
var restRequest = BuildWeemoPostRequest(endPointWithClientInfo, request);
var client = new RestClient();
client.ClientCertificates = new System.Security.Cryptography.X509Certificates.X509CertificateCollection();
client.ClientCertificates.Add(config.ClientCert);
return await client.ExecutePostTaskAsync(restRequest);
}
示例5: GetToken
public static async Task<IRestResponse<UserToken>> GetToken(string email, string password)
{
var client = new RestClient(SystemResource.GetTokenClient);
var request = new RestRequest(SystemResource.GetTokenRequest, Method.POST);
const string clientId = "6245c9d6cc3e51d82b88";
const string clientSecret = "4653add678ec42e2de1e8e7a0344402ed9bfe53c";
const string grantType = "password";
request.AddParameter("client_id", clientId);
request.AddParameter("client_secret", clientSecret);
request.AddParameter("grant_type", grantType);
request.AddParameter("email", email);
request.AddParameter("password", password);
return await client.ExecutePostTaskAsync<UserToken>(request);
}
示例6: SetProductKeyInvalid
public async void SetProductKeyInvalid(string key)
{
try
{
var client = new RestClient("http://" + _serverAdress);
var request = new RestRequest("setProductKeyInvalid.php", Method.POST);
request.AddParameter("productkeys_Key", key);
request.Timeout = 5000;
IRestResponse response = await client.ExecutePostTaskAsync(request);
if (response.ErrorException != null)
{
throw response.ErrorException;
}
}
catch (Exception e)
{
new Exception("Fehler aufgetreten: " + e);
}
}
示例7: AddProductToUser
public async void AddProductToUser(int productId, User user)
{
try
{
var client = new RestClient("http://" + _serverAdress);
var request = new RestRequest("AddProductToUser.php", Method.POST);
request.AddParameter("user_Email", user.user_Email);
request.AddParameter("product_ID", productId);
request.Timeout = 5000;
IRestResponse response = await client.ExecutePostTaskAsync(request);
if (response.ErrorException != null)
{
throw response.ErrorException;
}
}
catch (Exception e)
{
new Exception("Fehler aufgetreten: " + e);
}
}
示例8: AddUserToDatabase
public async void AddUserToDatabase(string username, string password)
{
try
{
var client = new RestClient("http://" + _serverAdress);
var request = new RestRequest("createUser.php", Method.POST);
request.AddParameter("user_Email", username);
//hashes the password before sending it to the server
request.AddParameter("user_Password", DependencyService.Get<IHash>().Sha512StringHash(password));
request.Timeout = 5000;
IRestResponse response = await client.ExecutePostTaskAsync(request);
await Task.Delay(3000);
if (response.ErrorException != null)
{
throw response.ErrorException;
}
}
catch (Exception e)
{
//Extra Exceptionhandling to void async
new Exception("AddUser Exception " + e);
}
}
示例9: CreateStreamingVideoAsync
/// <summary>
/// Creates a video stream attachment (upload to http://www.screen9.com/).
/// </summary>
/// <param name="video">The attachment.</param>
/// <param name="path">The path to the attachment file.</param>
/// <returns></returns>
/// <exception cref="System.NotImplementedException"></exception>
public async Task CreateStreamingVideoAsync(StreamingVideo video, string path)
{
// 1. Request a ticket for upload
var req = Connection.CreateRequest("videouploadticket");
var videoUploadTicket = await ExecuteAsync<VideoUploadTicket>(Connection, req);
// 2. Upload your video to screen9
var uploadClient = new RestClient(videoUploadTicket.UploadUrl);
if (Connection.HttpFactory != null) uploadClient.HttpFactory = Connection.HttpFactory;
req = new RestRequest();
req.AddParameter("auth", videoUploadTicket.Auth);
var fileName = Path.GetFileName(path);
byte[] bytes = null;
using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true))
using (var ms = new MemoryStream())
{
await fs.CopyToAsync(ms);
bytes = ms.ToArray();
}
req.AddFile("videofile", bytes, fileName, "application/octet-stream");
var resp = await uploadClient.ExecutePostTaskAsync(req);
if (resp.ErrorException != null) throw new IS24Exception(string.Format("Error uploading video {0}.", path), resp.ErrorException);
if ((int)resp.StatusCode >= 400) throw new IS24Exception(string.Format("Error uploading video {0}: {1}", path, resp.StatusDescription));
// 3. Post StreamingVideo attachment
req = Connection.CreateRequest("realestate/{id}/attachment", Method.POST);
req.AddParameter("id", RealEstate.Id, ParameterType.UrlSegment);
video.VideoId = videoUploadTicket.VideoId;
req.AddBody(video, typeof(Attachment));
var msg = await ExecuteAsync<Messages>(Connection, req);
var id = msg.ExtractCreatedResourceId();
if (!id.HasValue)
{
throw new IS24Exception(string.Format("Error creating attachment {0}: {1}", path, msg.ToMessage())) { Messages = msg };
}
video.Id = id.Value;
}
示例10: GetDeviceNamesByMacAsync
public async Task<IDictionary<string, string>> GetDeviceNamesByMacAsync()
{
using (await _lock.LockAsync())
{
if ((DateTime.UtcNow - _recentResultTimestamp).TotalMinutes < 10)
{
return _recentResult;
}
var result = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
if (string.IsNullOrEmpty(_username) || string.IsNullOrEmpty(_password))
{
_messageQueue.Publish(new NotifyUserMessage("Add mystrom configuration to config file."));
_recentResultTimestamp = DateTime.UtcNow;
return result;
}
var client = new RestClient("https://mystrom.ch");
var request = new RestRequest("app/de/auth/login");
request.AddParameter("email", _username);
request.AddParameter("password", _password);
request.AddParameter("remember", "false");
var response = await client.ExecutePostTaskAsync(request);
var cookies = response.Cookies;
request = new RestRequest("app/de/device/command");
request.AddHeader("Origin", "https://mystrom.ch");
request.AddHeader("Referer", "https://mystrom.ch/app/de/home");
request.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36");
request.AddHeader("Accept", "application/json, text/javascript, */*; q=0.01");
request.AddHeader("Content-Type", "application/json; charset=UTF-8");
request.AddHeader("X-Requested-With", "XMLHttpRequest");
request.AddJsonBody(new[] { new { type = "GetEcns" } });
foreach (var cookie in cookies)
{
request.AddCookie(cookie.Name, cookie.Value);
}
var dataResponse = await client.ExecutePostTaskAsync<List<EcnsDto>>(request);
if (dataResponse.Data != null && dataResponse.Data.Count > 0)
{
foreach (var device in dataResponse.Data[0].ecns)
{
result.Add(device.mac, device.name);
}
}
else
{
// TODO: retry
dataResponse.ToString();
}
_recentResult = new Dictionary<string, string>(result, StringComparer.OrdinalIgnoreCase);
_recentResultTimestamp = DateTime.UtcNow;
return result;
}
}
开发者ID:xpressive-websolutions,项目名称:Xpressive.Home.ProofOfConcept,代码行数:62,代码来源:MyStromDeviceNameService.cs
示例11: Signin
/// <summary>
/// Signin with a user
/// </summary>
/// <param name="user">The user</param>
/// <param name="ct">The cancellation token</param>
/// <returns>Bearer</returns>
public async Task<Bearer> Signin(Models.Account.User user, CancellationToken ct)
{
var watch = Stopwatch.StartNew();
var restClient = new RestClient(Constants.PopcornApiEndpoint);
var request = new RestRequest("/{segment}", Method.POST);
request.AddUrlSegment("segment", "oauth/token");
request.AddParameter("username", user.Username);
request.AddParameter("password", user.Password);
request.AddParameter("grant_type", "password");
var response = await restClient.ExecutePostTaskAsync(request, ct);
if (response.ErrorException != null)
{
throw new Exception();
}
if (response.StatusCode == HttpStatusCode.BadRequest)
{
}
var bearer =
await Task.Run(() => JsonConvert.DeserializeObject<Bearer>(response.Content), ct);
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
Logger.Debug(
$"Signin ({user.Username}, {user.Fullname}, {user.Email}) in {elapsedMs} milliseconds.");
return bearer;
}
示例12: DownloadNoIntroDat
private async static Task DownloadNoIntroDat(string sel_s, int delay=0)
{
if (delay > 0)
{
Console.WriteLine("[WARN] Must wait " + (delay / 1000 / 60).ToString() + " minutes due to throttling.");
await Task.Delay(delay);
}
Console.WriteLine("[INFO] Downloading " + sel_s.Replace('+', ' '));
var cookies = new CookieContainer();
var client = new RestClient("http://datomatic.no-intro.org/?page=download&fun=xml"); //Download the P/Clone
client.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.132 Safari/537.36";
client.CookieContainer = cookies; //DAT-o-MATIC relies on cookies
Console.WriteLine("[INFO] Waiting 1 minute to avoid throttling");
await Task.Delay(60000);
await client.ExecuteGetTaskAsync(new RestRequest()); //Save the session cookie
var setSystemRequest = new RestRequest(Method.POST);
setSystemRequest.AddParameter("application/x-www-form-urlencoded", "sel_s="+sel_s, ParameterType.RequestBody);
setSystemRequest.AddHeader("DNT", "1");
setSystemRequest.AddHeader("Referer", "http://datomatic.no-intro.org/index.php?page=download");
setSystemRequest.AddHeader("Host", "datomatic.no-intro.org");
setSystemRequest.AddHeader("Cache-Control", "max-age=0");
Console.WriteLine("[INFO] Waiting 1 minute to avoid throttling");
await Task.Delay(60000);
await client.ExecutePostTaskAsync(setSystemRequest); //POST the system.
var downloadRequest = new RestRequest(Method.POST);
downloadRequest.AddParameter("application/x-www-form-urlencoded", "Download=Download", ParameterType.RequestBody);
downloadRequest.AddHeader("DNT", "1");
downloadRequest.AddHeader("Referer", "http://datomatic.no-intro.org/index.php?page=download");
downloadRequest.AddHeader("Host", "datomatic.no-intro.org");
downloadRequest.AddHeader("Cache-Control", "max-age=0");
Console.WriteLine("[INFO] Waiting 1 minute to avoid throttling");
await Task.Delay(60000);
var response = await client.ExecuteTaskAsync(downloadRequest); //POST the download request
if (response.ResponseUri.OriginalString.StartsWith("http://datomatic.no-intro.org/index.php?page=message"))
{
Console.WriteLine("[WARN] Throttle detected, must wait 5 minutes before retrying");
await download.DownloadNoIntroDat(sel_s, delay + 600000);
}
else
{
File.WriteAllBytes(sel_s.Replace('+', ' ') + ".zip", response.RawBytes);
using (var package = new ZipArchive(new MemoryStream(response.RawBytes)))
{
foreach (var entry in package.Entries)
{
if (Path.GetExtension(entry.FullName) == ".dat")
{
entry.ExtractToFile("nointro_" + entry.Name, true);
}
}
}
Console.WriteLine("[INFO] Download Complete");
}
}
示例13: PostAuthAsync
public static async Task<AuthResponse> PostAuthAsync(string username, string password)
{
//curl https://api.spark.io/oauth/token -u spark:spark \
// -d grant_type=password -d [email protected] -d password=SuperSecret
//
// # A typical JSON response will look like this
// {
// "access_token": "<token_id>",
// "token_type": "bearer",
// "expires_in": 7776000
// }
// This is the equivalent SparkSharp way to ask for an auth token for the specified user (email).
// var auth = Spark.RESTCore.PostAuthAsync ("user", "password").Result;
// if (auth != null)
// Configuration.AccessToken = auth.Access_Token;
//
// Assumption: grant_type, client_id and client_secret parameters are hard coded because
// should be always the same.
var request = String.Format("https://api.spark.io/oauth/token");
var client = new RestClient ();
var grant_type = "password";
var client_id = "spark";
var client_secret = "spark";
var req = new RestRequest (request);
req.AddParameter ("grant_type", grant_type);
req.AddParameter ("client_id", client_id);
req.AddParameter ("client_secret", client_secret);
req.AddParameter ("username", username);
req.AddParameter ("password", password);
var response = await client.ExecutePostTaskAsync (req);
if (response.StatusCode == HttpStatusCode.OK) {
AuthResponse responses = (AuthResponse) JsonConvert.DeserializeObject<AuthResponse>(response.Content);
return responses;
}
return null;
}