本文整理汇总了C#中System.Net.Http.FormUrlEncodedContent.ReadAsStringAsync方法的典型用法代码示例。如果您正苦于以下问题:C# FormUrlEncodedContent.ReadAsStringAsync方法的具体用法?C# FormUrlEncodedContent.ReadAsStringAsync怎么用?C# FormUrlEncodedContent.ReadAsStringAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Http.FormUrlEncodedContent
的用法示例。
在下文中一共展示了FormUrlEncodedContent.ReadAsStringAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Ctor
public void Ctor ()
{
var s = new List<KeyValuePair<string, string>> () {
new KeyValuePair<string, string> ("key", "44"),
new KeyValuePair<string, string> ("key 2", "&+/Ž@:=")
};
using (var m = new FormUrlEncodedContent (s)) {
Assert.AreEqual ("application/x-www-form-urlencoded", m.Headers.ContentType.MediaType, "#1");
Assert.AreEqual (37, m.Headers.ContentLength, "#2");
Assert.AreEqual ("key=44&key+2=%26%2B%2F%C5%BD%40%3A%3D", m.ReadAsStringAsync ().Result, "#3");
}
s = new List<KeyValuePair<string, string>> ();
using (var m = new FormUrlEncodedContent (s)) {
Assert.AreEqual ("application/x-www-form-urlencoded", m.Headers.ContentType.MediaType, "#11");
Assert.AreEqual (0, m.Headers.ContentLength, "#12");
Assert.AreEqual ("", m.ReadAsStringAsync ().Result, "#13");
}
s = new List<KeyValuePair<string, string>> () {
new KeyValuePair<string, string> ( "key", ""),
new KeyValuePair<string, string> ( "key+ 2", null)
};
using (var m = new FormUrlEncodedContent (s)) {
Assert.AreEqual ("application/x-www-form-urlencoded", m.Headers.ContentType.MediaType, "#21");
Assert.AreEqual (14, m.Headers.ContentLength, "#22");
Assert.AreEqual ("key=&key%2B+2=", m.ReadAsStringAsync ().Result, "#23");
}
}
示例2: SendSms
public async Task<SendSmsResult> SendSms(string message)
{
var queryParameter = new[]
{
new KeyValuePair<string, string>("user", _user),
new KeyValuePair<string, string>("pass", _pass),
new KeyValuePair<string, string>("msg", message)
};
HttpContent content = new FormUrlEncodedContent(queryParameter);
var query = await content.ReadAsStringAsync();
var response = await _httpClient.GetAsync(new Uri(_smsapiUri, "/sendmsg?" + query));
switch (response.StatusCode)
{
case HttpStatusCode.OK:
return SendSmsResult.Sent;
case HttpStatusCode.BadRequest:
return SendSmsResult.MissingParameter;
case HttpStatusCode.PaymentRequired:
return SendSmsResult.Throttled;
case HttpStatusCode.Forbidden:
return SendSmsResult.ServiceNotActivated;
case HttpStatusCode.InternalServerError:
return SendSmsResult.ServerError;
}
return SendSmsResult.ServerError;
}
示例3: GenerateSHA512Signature
public string GenerateSHA512Signature(FormUrlEncodedContent request)
{
HMAC digester = new HMACSHA512(this.PrivateKeyBytes);
StringBuilder hex = new StringBuilder();
byte[] requestBytes = System.Text.Encoding.ASCII.GetBytes(request.ReadAsStringAsync().Result);
return BitConverter.ToString(digester.ComputeHash(requestBytes)).Replace("-", "").ToLower();
}
示例4: DebugPrintAnalyticsOutput
private async void DebugPrintAnalyticsOutput(Task<string> resultTask, Dictionary<string, string> hitData)
{
using (var form = new FormUrlEncodedContent(hitData))
{
var result = await resultTask.ConfigureAwait(false);
var formData = await form.ReadAsStringAsync().ConfigureAwait(false);
Debug.WriteLine($"Request: POST {_serverUrl} Data: {formData}");
Debug.WriteLine($"Output of analytics: {result}");
}
}
示例5: GetQueryString
private string GetQueryString(ApiRequest request)
{
string xml = _xmlPipeline.Serialize(request);
List<KeyValuePair<string, string>> values = GetQueryStringValues(xml);
string query;
using (var content = new FormUrlEncodedContent(values))
{
query = content.ReadAsStringAsync().Result;
}
return query;
}
示例6: GetLoginPage
private async Task<GetLoginPageResult> GetLoginPage()
{
var result = new GetLoginPageResult();
var queryParameter = new[]
{
new KeyValuePair<string, string>("locale", "en_US"),
new KeyValuePair<string, string>("state", "bfh"),
new KeyValuePair<string, string>("redirect_uri",
"https://battlelog.battlefield.com/sso/?tokentype=code"),
new KeyValuePair<string, string>("response_type", "code"),
new KeyValuePair<string, string>("client_id", "battlelog"),
new KeyValuePair<string, string>("display", "web/login")
};
HttpContent content = new FormUrlEncodedContent(queryParameter);
var query = await content.ReadAsStringAsync();
var uri = new Uri("https://accounts.ea.com/connect/auth?" + query, UriKind.Absolute);
var response = await _httpClient.GetAsync(uri);
var source = await response.Content.ReadAsStringAsync();
var parameters = response.RequestMessage.RequestUri.Query.Remove(0, 1).Split('&');
foreach (var parameter in parameters)
{
var parameterSplitted = parameter.Split('=');
var key = parameterSplitted[0];
var value = WebUtility.UrlDecode(parameterSplitted[1]);
if (key == "execution")
{
result.Execution = value;
}
else if (key == "initref")
{
result.Initref = value;
}
}
// If HttpUtility is available in .Net 5
//var queryDuringRedirect = response.RequestMessage.RequestUri.ParseQueryString();
//result.Execution = queryDuringRedirect["execution"];
//result.Initref = queryDuringRedirect["initref"];
return result;
}
示例7: SetupRequestUrl
private void SetupRequestUrl()
{
using (var content = new FormUrlEncodedContent(new KeyValuePair<string, string>[]
{
new KeyValuePair<string, string>("client", ClientName),
new KeyValuePair<string, string>("key", ApiKey),
new KeyValuePair<string, string>("appver", ClientVersion),
new KeyValuePair<string, string>("pver", ProtocolVersion)
}
))
{
RequestUrl = HttpClient.BaseAddress.ToString() + content.ReadAsStringAsync().Result;
}
}
示例8: BuildGetTokenUri
private Uri BuildGetTokenUri(string clientId, string clientSecret, string redirectUri, string code)
{
var query = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("client_id", clientId),
new KeyValuePair<string, string>("client_secret", clientSecret),
new KeyValuePair<string, string>("code", code),
new KeyValuePair<string, string>("redirect_uri", redirectUri)
});
var uriBuilder = new UriBuilder(OAuthInfo.SlackOAuthUri);
uriBuilder.Query = query.ReadAsStringAsync().Result;
return uriBuilder.Uri;
}
示例9: HttpClient_PostAsync
public async Task HttpClient_PostAsync(string requestUrl, string responseContent)
{
var mockResponse = new HttpResponseMessage(HttpStatusCode.OK) {Content = new StringContent(responseContent)};
var mockPostContent = new FormUrlEncodedContent(PostContent.ToArray());
var mockPostContentString = await mockPostContent.ReadAsStringAsync().ConfigureAwait(false);
var httpClient = new HttpClient(new MockHttpMessageHandler(requestUrl, mockResponse));
var httpResponse = await httpClient.PostAsync(requestUrl, mockPostContent).ConfigureAwait(false);
var stringResponse = string.Empty;
if (httpResponse.Content != null)
stringResponse = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Assert.Equal(mockPostContentString, "Name=bob&Address=Ireland&Phone=12345");
Assert.Equal(responseContent, stringResponse);
}
示例10: SubmitAsync
/// <summary>
/// submit this form, using a specified HttpClient.
/// </summary>
/// <remarks>
/// the request will be set up from the form values.
/// You can set up other options (like user-agent, timeout, cookies) before executing.
/// </remarks>
/// <returns>an async task.</returns>
/// <exception cref="System.ArgumentException">
/// if the form's absolute action URL cannot be determined.
/// Make sure you pass the document's base URI when parsing.
/// </exception>
public Task<HttpResponseMessage> SubmitAsync(HttpClient client)
{
string action = HasAttr("action") ? AbsUrl("action") : BaseUri;
Validate.NotEmpty(action, "Could not determine a form action URL for submit. Ensure you set a base URI when parsing.");
var data = new FormUrlEncodedContent(this.FormData);
if (string.Equals(Attr("method"), "POST", StringComparison.OrdinalIgnoreCase))
{
// POST
return client.PostAsync(action, data);
}
else
{
// GET
var actionUrl = new UriBuilder(action);
actionUrl.Query = data.ReadAsStringAsync().Result;
return client.GetAsync(actionUrl.Uri);
}
}
示例11: GetTorrents
public async Task<IList<Torrent>> GetTorrents(Filter filter = Filter.All, string category = null)
{
await CheckAuthentification();
var keyValuePairs = new KeyValuePair<string, string>[2];
keyValuePairs.SetValue(new KeyValuePair<string, string>("filter", filter.ToString().ToLower()), 0);
if (category != null)
{
keyValuePairs.SetValue(new KeyValuePair<string, string>("category", category), 1);
}
HttpContent content = new FormUrlEncodedContent(keyValuePairs);
var uri = new Uri("/query/torrents?" + await content.ReadAsStringAsync(), UriKind.Relative);
var response = await _httpClient.GetAsync(uri);
var jsonStr = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<IList<Torrent>>(jsonStr);
}
示例12: FormatQueryString
protected string FormatQueryString(string requestUri, IEnumerable<KeyValuePair<string, string>> parameters = null)
{
try
{
string query;
using (var content = new FormUrlEncodedContent(parameters ?? new HashSet<KeyValuePair<string, string>>()))
{
query = content.ReadAsStringAsync().Result;
}
//requestUri += requestUri.IndexOf('?') == -1 ? ("?" + query) : (String.IsNullOrEmpty(query) ? "" : "&" + query);
requestUri += requestUri.IndexOf('?') == -1 ? (String.IsNullOrEmpty(query) ? "" : "?" + query) : (String.IsNullOrEmpty(query) ? "" : "&" + query);
return requestUri;
}
catch (Exception)
{
throw;
}
}
示例13: QueryMyObjects
public async System.Threading.Tasks.Task<IServiceResponse<PagedResult<MyObject>>> QueryMyObjects(IServiceRequest<PagedQuery> query)
{
query.MustNotBeNull("query");
//this method of query strings from object content can be refactored. However, it will have to be a more complex solution
//that is completely generic and handles nested objects in the same way that the server libraries expect to see.
//for now, this merely demonstrates the core principle.
Dictionary<string, string> queryKeyValues = new Dictionary<string, string>();
//some system that relies on a similar mechanism to Model Binding should be used to convert to strings. That uses
//the TypeDescriptor.GetConverter mechanism, so we couuld do the same.
queryKeyValues["Page"] = Convert.ToString(query.Argument.Page);
queryKeyValues["PageSize"] = Convert.ToString(query.Argument.PageSize);
string queryString = null;
using (var tempContent = new FormUrlEncodedContent(queryKeyValues))
{
//why use this? It handles the url encoding - and doesn't require System.Web (another popular
//solution uses HttpUtility.ParseQueryString - but client code has no business referencing System.Web).
queryString = await tempContent.ReadAsStringAsync();
}
return await _requestManager.Get<ApiServiceResponse<PagedResult<MyObject>>>(string.Concat("api/MyObjects?", queryString), query);
}
示例14: MakeQuery
static Task<string> MakeQuery(Dictionary<string, string> data)
{
using (var content = new FormUrlEncodedContent(data))
return content.ReadAsStringAsync();
}
示例15: GetAppOnlyAccessTokenWithHttpRequest
// Get the access token via straight http post request doing client credential flow
private async Task<String> GetAppOnlyAccessTokenWithHttpRequest(string resource, string tenantId)
{
/**
* use the tenant specific endpoint for requesting the app-only access token
*/
string tokenIssueEndpoint = appConfig.TokenIssueingUri.Replace("common", tenantId);
/**
* sign the assertion with the private key
*/
string certfile = Server.MapPath(appConfig.ClientCertificatePfx);
X509Certificate2 cert = new X509Certificate2(
certfile,
appConfig.ClientCertificatePfxPassword,
X509KeyStorageFlags.MachineKeySet);
/**
* Example building assertion using Json Tokenhandler.
* Sort of cheating, but just if someone wonders ... there are always more ways to do something :-)
*/
Dictionary<string, string> claims = new Dictionary<string, string>()
{
{ "sub", appConfig.ClientId },
{ "jti", Guid.NewGuid().ToString() },
};
JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
X509SigningCredentials signingCredentials = new X509SigningCredentials(cert, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
JwtSecurityToken selfSignedToken = new JwtSecurityToken(
appConfig.ClientId,
tokenIssueEndpoint,
claims.Select(c => new Claim(c.Key, c.Value)),
DateTime.UtcNow,
DateTime.UtcNow.Add(TimeSpan.FromMinutes(15)),
signingCredentials);
string signedAssertion = tokenHandler.WriteToken(selfSignedToken);
//---- End example with Json Tokenhandler... now to the fun part doing it all ourselves ...
/**
* Example building assertion from scratch with Crypto APIs
*/
JObject clientAssertion = new JObject();
clientAssertion.Add("aud", tokenIssueEndpoint);
clientAssertion.Add("iss", appConfig.ClientId);
clientAssertion.Add("sub", appConfig.ClientId);
clientAssertion.Add("jti", Guid.NewGuid().ToString());
clientAssertion.Add("nbf", WebConvert.EpocTime(DateTime.UtcNow + TimeSpan.FromMinutes(-5)));
clientAssertion.Add("exp", WebConvert.EpocTime(DateTime.UtcNow + TimeSpan.FromMinutes(15)));
string assertionPayload = clientAssertion.ToString(Newtonsoft.Json.Formatting.None);
X509AsymmetricSecurityKey x509Key = new X509AsymmetricSecurityKey(cert);
RSACryptoServiceProvider rsa = x509Key.GetAsymmetricAlgorithm(SecurityAlgorithms.RsaSha256Signature, true) as RSACryptoServiceProvider;
RSACryptoServiceProvider newRsa = GetCryptoProviderForSha256(rsa);
SHA256Cng sha = new SHA256Cng();
JObject header = new JObject(new JProperty("alg", "RS256"));
string thumbprint = WebConvert.Base64UrlEncoded(WebConvert.HexStringToBytes(cert.Thumbprint));
header.Add(new JProperty("x5t", thumbprint));
string encodedHeader = WebConvert.Base64UrlEncoded(header.ToString());
string encodedPayload = WebConvert.Base64UrlEncoded(assertionPayload);
string signingInput = String.Concat(encodedHeader, ".", encodedPayload);
byte[] signature = newRsa.SignData(Encoding.UTF8.GetBytes(signingInput), sha);
signedAssertion = string.Format("{0}.{1}.{2}",
encodedHeader,
encodedPayload,
WebConvert.Base64UrlEncoded(signature));
/**
* build the request payload
*/
FormUrlEncodedContent tokenRequestForm;
tokenRequestForm = new FormUrlEncodedContent(
new[] {
new KeyValuePair<string,string>("resource", appConfig.ExchangeResourceUri),
new KeyValuePair<string,string>("client_id", appConfig.ClientId),
new KeyValuePair<string,string>("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),
new KeyValuePair<string,string>("client_assertion", signedAssertion),
new KeyValuePair<string,string>("grant_type","client_credentials"),
}
);
/*
* Do the web request
*/
HttpClient client = new HttpClient();
Task<string> requestString = tokenRequestForm.ReadAsStringAsync();
StringContent requestContent = new StringContent(requestString.Result);
requestContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
requestContent.Headers.Add("client-request-id", System.Guid.NewGuid().ToString());
requestContent.Headers.Add("return-client-request-id", "true");
//.........这里部分代码省略.........