本文整理汇总了C#中System.Net.Http.FormUrlEncodedContent类的典型用法代码示例。如果您正苦于以下问题:C# FormUrlEncodedContent类的具体用法?C# FormUrlEncodedContent怎么用?C# FormUrlEncodedContent使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
FormUrlEncodedContent类属于System.Net.Http命名空间,在下文中一共展示了FormUrlEncodedContent类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: MashapeFacebookLogin
public async Task MashapeFacebookLogin()
{
//NOTE: Check App.xaml.cs for the variables that you need to fill in
var targeturi = "https://ismaelc-facebooktest.p.mashape.com/oauth_url";
var client = new System.Net.Http.HttpClient();
HttpContent content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("consumerKey", App.ConsumerKey),
new KeyValuePair<string, string>("consumerSecret", App.ConsumerSecret),
new KeyValuePair<string, string>("callbackUrl", App.CallbackUrl)
});
content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
content.Headers.Add("X-Mashape-Authorization", App.MashapeHeader);
progressRing.IsActive = true;
btnLogin.IsEnabled = false;
var response = await client.PostAsync(targeturi, content);
progressRing.IsActive = false;
btnLogin.IsEnabled = true;
if (response.IsSuccessStatusCode)
{
string respContent = await response.Content.ReadAsStringAsync();
string loginUrl = await Task.Run(() => JsonObject.Parse(respContent).GetNamedString("url"));
WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(
WebAuthenticationOptions.None,
new Uri(loginUrl),
new Uri(App.CallbackUrl));
if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
{
btnLogin.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
var callBackUrl = WebAuthenticationResult.ResponseData.ToString();
//Where's ParseQueryString when you need it...
App.AccessToken = GetParameter(callBackUrl, "accessToken");
//App.AccessSecret = GetParameter(callBackUrl, "accessSecret");
}
else if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
{
throw new InvalidOperationException("HTTP Error returned by AuthenticateAsync() : " + WebAuthenticationResult.ResponseErrorDetail.ToString());
}
else
{
// The user canceled the authentication
}
}
else
{
//The POST failed, so update the UI accordingly
//txtBlockResult.Text = "Error";
}
}
示例2: ChangeUserProfile
public static async Task<bool> ChangeUserProfile(String name, String url, String description, String location,
UserAccountEntity userAccountEntity)
{
if (userAccountEntity.GetAccessToken().Equals("refresh"))
{
await Auth.RefreshAccessToken(userAccountEntity);
}
var param = new Dictionary<String, String>();
if (!string.IsNullOrEmpty(name)) param.Add("name", name);
if (!string.IsNullOrEmpty(url)) param.Add("url", url);
if (!string.IsNullOrEmpty(location)) param.Add("location", location);
if (!string.IsNullOrEmpty(description)) param.Add("description", description);
var theAuthClient = new HttpClient();
HttpContent header = new FormUrlEncodedContent(param);
var request = new HttpRequestMessage(HttpMethod.Post, EndPoints.ACCOUNT_UPDATE) {Content = header};
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", userAccountEntity.GetAccessToken());
try
{
HttpResponseMessage response = await theAuthClient.SendAsync(request);
return response.IsSuccessStatusCode;
}
catch (Exception)
{
return false;
}
}
示例3: SetupAutoCADIOContainer
/// <summary>
/// Does setup of AutoCAD IO.
/// This method will need to be invoked once before any other methods of this
/// utility class can be invoked.
/// </summary>
/// <param name="autocadioclientid">AutoCAD IO Client ID - can be obtained from developer.autodesk.com</param>
/// <param name="autocadioclientsecret">AutoCAD IO Client Secret - can be obtained from developer.autodesk.com</param>
public static void SetupAutoCADIOContainer(String autocadioclientid, String autocadioclientsecret)
{
try
{
String clientId = autocadioclientid;
String clientSecret = autocadioclientsecret;
Uri uri = new Uri("https://developer.api.autodesk.com/autocad.io/us-east/v2/");
container = new AIO.Operations.Container(uri);
container.Format.UseJson();
using (var client = new HttpClient())
{
var values = new List<KeyValuePair<string, string>>();
values.Add(new KeyValuePair<string, string>("client_id", clientId));
values.Add(new KeyValuePair<string, string>("client_secret", clientSecret));
values.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
var requestContent = new FormUrlEncodedContent(values);
var response = client.PostAsync("https://developer.api.autodesk.com/authentication/v1/authenticate", requestContent).Result;
var responseContent = response.Content.ReadAsStringAsync().Result;
var resValues = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseContent);
_accessToken = resValues["token_type"] + " " + resValues["access_token"];
if (!string.IsNullOrEmpty(_accessToken))
{
container.SendingRequest2 += (sender, e) => e.RequestMessage.SetHeader("Authorization", _accessToken);
}
}
}
catch (System.Exception ex)
{
Console.WriteLine(String.Format("Error while connecting to https://developer.api.autodesk.com/autocad.io/v2/", ex.Message));
container = null;
throw;
}
}
示例4: GetAuthorizationToken
/// <summary>
/// Makes a HTTP call to the OAuth2 endpoint for getting the OAuth2 token that can be used for
/// further HTTP communication with Dinero.
/// </summary>
/// <returns></returns>
public async Task<AuthorizationToken> GetAuthorizationToken()
{
var clientInfo = _client.Id + ":" + _client.Secret;
using (var client = new HttpClient())
{
var content = new FormUrlEncodedContent(_bodyContentParameters.GetBodyParameters());
var request = new HttpRequestMessage
{
RequestUri = _oAuth2TokenEndpoint,
Method = HttpMethod.Post,
Content = content
};
request.Headers.Add("Authorization", string.Format("Basic {0}", clientInfo.Base64Encode()));
var result = await client.SendAsync(request).ConfigureAwait(false);
var resultContent = await result.Content.ReadAsStringAsync().ConfigureAwait(false);
var definition = new { Access_Token = "", Token_Type = "", Expires_In = 0, Refresh_Token = ""};
try
{
var resultObj = JsonConvert.DeserializeAnonymousType(resultContent, definition);
if (resultObj.Access_Token == null)
throw new DineroAuthenticationException("Could not retrieve access token.");
return new AuthorizationToken(resultObj.Access_Token, DateTime.Now.AddSeconds(resultObj.Expires_In).AddMinutes(-5), resultObj.Refresh_Token);
}
catch (Exception e)
{
throw new DineroAuthenticationException("Could not retrieve access token.",e);
}
}
}
示例5: Authenticate
public async Task Authenticate()
{
var loginRequestData = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("username", _username),
new KeyValuePair<string, string>("password", _password)
});
var response = await httpClient.PostAsync("/user/login", loginRequestData);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
dynamic jsonData = JsonConvert.DeserializeObject(responseBody);
if (jsonData == null)
throw new NestException(response);
if (jsonData.urls == null)
throw new NestException(response);
AccessToken = jsonData.access_token;
AccessTokenExpiration = jsonData.expires_in;
UserId = jsonData.userid;
var urls = jsonData.urls;
ApiUrl = urls.rubyapi_url;
TransportApiBaseAddress = urls.transport_url;
WeatherUrl = urls.weather_url;
}
示例6: ChkVerifyCodeAnsyn
public static async Task<bool> ChkVerifyCodeAnsyn(string verifyNo)
{
try
{
var handler = new HttpClientHandler() { CookieContainer = cookieContainers, AllowAutoRedirect = true, AutomaticDecompression = DecompressionMethods.GZip };
using (var httpClient = new HttpClient(handler))
{
httpClient.DefaultRequestHeaders.Add("Host", "kyfw.12306.cn");
httpClient.DefaultRequestHeaders.Add("Origin", ConstantKey.loginorigin);
httpClient.DefaultRequestHeaders.Add("Referer", ConstantKey.loginRefer);
httpClient.DefaultRequestHeaders.Add("UserAgent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131");
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, errors) => true;
// 构造POST参数
var data = new FormUrlEncodedContent(new Dictionary<string, string>()
{
{"randCode", verifyNo},
{"rand", "sjrand"}
});
var response = await httpClient.PostAsync(ConstantKey.loginChkVcode, data);
response.EnsureSuccessStatusCode();
string content = await response.Content.ReadAsStringAsync();
if (string.IsNullOrEmpty(content) || !content.Contains("Y") || !content.Contains("true")) return false;
return true;
}
}
catch (Exception ex)
{
return false;
}
}
示例7: CreateTag
public string CreateTag(Tag model, UserData userData)
{
try
{
client = new HttpClient();
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("name", model.name));
HttpContent content = new FormUrlEncodedContent(postData);
content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
content.Headers.Add("Timestamp", userData.Timestamp.ToString());
content.Headers.Add("Digest", userData.AuthenticationHash);
content.Headers.Add("Public-Key", userData.PublicKey);
client.PostAsync("http://localhost:3000/tag", content)
.ContinueWith(postTask =>
{
postTask.Result.EnsureSuccessStatusCode();
var result = postTask.Result.Content.ReadAsStringAsync();
client.Dispose();
return result;
});
}
catch (Exception ex)
{
throw ex;
}
return null;
}
示例8: Post
public static string Post(string url, PostBody postBody, int timeout = 5000)
{
try
{
Logger.Debug($"Post\t{url}");
using (var handler = new HttpClientHandler() { CookieContainer = new CookieContainer() })
using (var client = new HttpClient(handler))
{
var content = new FormUrlEncodedContent(postBody.Body);
var magicCodeName = string.Empty;
if (Config.TryGet("MagicCodeType", out magicCodeName))
{
var magicCodeValue = Config.TryGet("MagicCodeValue", "");
var magicCodePath = Config.TryGet("MagicCodePath", "/");
var magicCodeDomain = Config.TryGet("MagicCodeDomain", ".baidu.com");
handler.CookieContainer.Add(new Cookie(magicCodeName, magicCodeValue, magicCodePath, magicCodeDomain));
}
var result = client.PostAsync(url, content).Result;
result.EnsureSuccessStatusCode();
return result.Content.ReadAsStringAsync().Result;
}
}
catch (Exception e)
{
Logger.Error(e.ToString());
return e.Message;
}
}
示例9: PostStringAsync
public async Task<String> PostStringAsync(Uri uri, IDictionary<String, String> content) {
using (var http = new HttpClient()) {
var formContent = new FormUrlEncodedContent(content);
var response = await http.PostAsync(uri, formContent);
return await response.Content.ReadAsStringAsync();
}
}
示例10: CheckStatusCodeIs
public Step CheckStatusCodeIs(HttpStatusCode codeToMatch)
{
var formContent = new FormUrlEncodedContent(_formContent);
SetUpDefaultHeaders();
Stopwatch stopWatch = Stopwatch.StartNew();
var task = Post(formContent);
string htmlContent = task.Result.Content.ReadAsStringAsync().Result;
stopWatch.Stop();
Console.WriteLine("Took {0} Milliseconds", stopWatch.ElapsedMilliseconds);
if (!string.IsNullOrEmpty(htmlContent))
{
if (htmlContent.Contains("__EVENTVALIDATION"))
{
CurrentEventValidation = HttpScraper.GetEventValidationFromHtml(htmlContent);
}
if (htmlContent.Contains("__VIEWSTATE"))
{
CurrentViewState = HttpScraper.GetViewStateFromHtml(htmlContent);
}
}
if (task.Result != null)
{
task.Result.StatusCode.Should().Be(codeToMatch);
}
else
{
throw new Exception("Http Status code is null");
}
Step.CurrentEventValidation = CurrentEventValidation;
Step.CurrentViewState = CurrentViewState;
Step.CurrentHtml = htmlContent;
Dispose();
return Step;
}
示例11: GetAuthorizationCode
private async Task<SuccessfulAuthenticationResponse> GetAuthorizationCode(AuthorizationGrantRequest request)
{
var url = request.Uri;
var data = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("scope", "openid"),
new KeyValuePair<string, string>("response_type", "code"),
new KeyValuePair<string, string>("client_id", request.ClientId),
new KeyValuePair<string, string>("client_secret", request.ClientSecret),
new KeyValuePair<string, string>("prompt", "none"),
new KeyValuePair<string, string>("redirect_uri", request.RedirectUri),
new KeyValuePair<string, string>("username", request.Username),
new KeyValuePair<string, string>("password", request.Password),
});
var client = new HttpClient();
var response = await client.PostAsync(url, data);
var content = await response.Content.ReadAsStringAsync();
if (response.StatusCode != System.Net.HttpStatusCode.OK)
{
var error = JsonConvert
.DeserializeObject<AuthenticationErrorResponse>
(content);
throw new Exception(error.error + ": " + error.error_description);
}
else
{
return JsonConvert
.DeserializeObject<SuccessfulAuthenticationResponse>
(content);
}
}
示例12: Execute
public async Task<JObject> Execute()
{
if (!NetworkInterface.GetIsNetworkAvailable())
throw new Exception("Network is not available.");
var uri = GetFullUri();
#if DEBUG
Debug.WriteLine("Invoking " + uri);
#endif
JObject response = null;
var httpClient = new HttpClient();
if (_method == "GET")
{
HttpResponseMessage responseMessage = await httpClient.GetAsync(uri);
var content = await responseMessage.Content.ReadAsStringAsync();
if (!string.IsNullOrEmpty(content))
response = JObject.Parse(content);
}
else
{
var postContent = new FormUrlEncodedContent(_parameters);
postContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
HttpResponseMessage responseMessage = await httpClient.PostAsync(uri, postContent);
var content = await responseMessage.Content.ReadAsStringAsync();
if (!string.IsNullOrEmpty(content))
response = JObject.Parse(content);
}
return response;
}
示例13: SendCommentReply
public static async Task<bool> SendCommentReply(string userId,string comment)
{
try
{
var client = await MalHttpContextProvider.GetHttpContextAsync();
var contentPairs = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("profileMemId", userId),
new KeyValuePair<string, string>("commentText", comment),
new KeyValuePair<string, string>("area", "2"),
new KeyValuePair<string, string>("csrf_token", client.Token),
new KeyValuePair<string, string>("commentSubmit", "1")
};
var content = new FormUrlEncodedContent(contentPairs);
var response =
await client.PostAsync("/addcomment.php", content);
//edit comment function - not sure what it does
// /includes/ajax.inc.php?t=73
//com id - token
//id = 31985758 & csrf_token = dfsdfsd
//client.PostAsync("/includes/ajax.inc.php?t=73")
return response.IsSuccessStatusCode || response.StatusCode == HttpStatusCode.SeeOther;
}
catch (WebException)
{
MalHttpContextProvider.ErrorMessage("Messages");
return false;
}
}
示例14: PlayGame
private static async void PlayGame(string[] splittedInput)
{
var gameId = splittedInput[1];
var x = splittedInput[2];
var y = splittedInput[3];
var httpClient = new HttpClient();
using (httpClient)
{
httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("GameId", gameId),
new KeyValuePair<string, string>("PositionX", x),
new KeyValuePair<string, string>("PositionY", y),
});
var response = await httpClient.PostAsync("http://localhost:62859/api/Games/play", content);
if (!response.IsSuccessStatusCode)
{
var messageObj = response.Content.ReadAsAsync<ErrorDTO>().Result;
Console.WriteLine(messageObj.Message + "; Description: " + messageObj.ExceptionMessage);
}
else
{
var gameid = response.Content.ReadAsStringAsync().Result;
Console.WriteLine("Game is running, id: " + gameid);
}
}
}
示例15: SendComment
public static async Task<bool> SendComment(string username,string userId,string comment)
{
try
{
var client = await MalHttpContextProvider.GetHttpContextAsync();
var contentPairs = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("profileMemId", userId),
new KeyValuePair<string, string>("commentText", comment),
new KeyValuePair<string, string>("profileUsername", username),
new KeyValuePair<string, string>("csrf_token", client.Token),
new KeyValuePair<string, string>("commentSubmit", "Submit Comment")
};
var content = new FormUrlEncodedContent(contentPairs);
var response =
await client.PostAsync("/addcomment.php", content);
return response.IsSuccessStatusCode || response.StatusCode == HttpStatusCode.SeeOther;
}
catch (WebException)
{
MalHttpContextProvider.ErrorMessage("Messages");
return false;
}
}