本文整理汇总了C#中HttpClient.SendRequestAsync方法的典型用法代码示例。如果您正苦于以下问题:C# HttpClient.SendRequestAsync方法的具体用法?C# HttpClient.SendRequestAsync怎么用?C# HttpClient.SendRequestAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类HttpClient
的用法示例。
在下文中一共展示了HttpClient.SendRequestAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: HttpPost
public static async void HttpPost(string cid, string cname, string cimage, string cdream, string fid, string fname,string fimage,string fdream)
{
try
{
HttpClient httpClient = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, new Uri(Config.apiUserFollow));
HttpFormUrlEncodedContent postData = new HttpFormUrlEncodedContent(
new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("cphone", cid),
new KeyValuePair<string, string>("cname", cname),
new KeyValuePair<string, string>("cimage", cimage),
new KeyValuePair<string, string>("cdream", cdream),
new KeyValuePair<string, string>("fphone", fid),
new KeyValuePair<string, string>("fname", fname),
new KeyValuePair<string, string>("fimage", fimage),
new KeyValuePair<string, string>("fdream", fdream),
}
);
request.Content = postData;
HttpResponseMessage response = await httpClient.SendRequestAsync(request);
string responseString = await response.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
HelpMethods.Msg(ex.Message.ToString());
}
}
示例2: GetBearerTokenAsync
async Task GetBearerTokenAsync()
{
var req = new HttpRequestMessage(HttpMethod.Post, new Uri(OAuth2Token));
req.Headers.Add("Authorization", "Basic " + BasicToken);
req.Headers.Add("User-Agent", UserAgent);
req.Headers.Add("Expect", "100-continue");
req.Content = new HttpStringContent("grant_type=client_credentials", Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/x-www-form-urlencoded");
var baseFilter = new HttpBaseProtocolFilter
{
AutomaticDecompression = SupportsCompression,
ProxyCredential = ProxyCredential,
UseProxy = UseProxy
};
using (var client = new HttpClient(baseFilter))
{
var msg = await client.SendRequestAsync(req);
await TwitterErrorHandler.ThrowIfErrorAsync(msg);
string response = await msg.Content.ReadAsStringAsync();
var responseJson = JsonMapper.ToObject(response);
BearerToken = responseJson.GetValue<string>("access_token");
}
}
示例3: SendHeadRequestAsync
public async static Task<HttpResponseMessage> SendHeadRequestAsync(Uri url)
{
var filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
filter.CacheControl.WriteBehavior = Windows.Web.Http.Filters.HttpCacheWriteBehavior.NoCache;
using (var httpClient = new HttpClient(filter))
{
try
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Head, url);
HttpResponseMessage response = await httpClient.SendRequestAsync(request);
#if DEBUG
Logger.Log("Sending head request with: " + url);
#endif
return response;
}
catch (Exception e)
{
#if DEBUG
Logger.Log("GetBufferAsync exception for url: " + url + " HRESULT 0x" + e.HResult.ToString("x"));
#endif
return null;
}
}
}
示例4: SetupPushNotificationChannelForApplicationAsync
public async void SetupPushNotificationChannelForApplicationAsync(string token, string arguments)
{
if (string.IsNullOrWhiteSpace(token))
{
throw new ArgumentException("you should add you app token");
}
//var encryptedArguments = Helper.Encrypt(arguments, "cnblogs", "somesalt");
_channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
var content = new HttpFormUrlEncodedContent(new[] {
new KeyValuePair<string, string>("arguments", arguments),
new KeyValuePair<string, string>("token", token),
new KeyValuePair<string, string>("uri", _channel.Uri),
new KeyValuePair<string, string>("uuid", GetUniqueDeviceId())
});
var request = new HttpRequestMessage(HttpMethod.Post, new Uri(server));
request.Content = content;
var client = new HttpClient();
var response = await client.SendRequestAsync(request);
_channel.PushNotificationReceived += _channel_PushNotificationReceived;
}
示例5: InvalidateAsync
public async Task InvalidateAsync()
{
EncodeCredentials();
var req = new HttpRequestMessage(HttpMethod.Post, new Uri(OAuth2InvalidateToken));
req.Headers.Add("Authorization", "Basic " + BasicToken);
req.Headers.Add("User-Agent", UserAgent);
req.Headers.Add("Expect", "100-continue");
req.Content = new HttpStringContent("access_token=" + BearerToken, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/x-www-form-urlencoded");
var baseFilter = new HttpBaseProtocolFilter
{
AutomaticDecompression = true
};
//var handler = new HttpClientHandler();
//if (handler.SupportsAutomaticDecompression)
// handler.AutomaticDecompression = DecompressionMethods.GZip;
//if (Proxy != null && handler.SupportsProxy)
// handler.Proxy = Proxy;
using (var client = new HttpClient(baseFilter))
{
var msg = await client.SendRequestAsync(req);
await TwitterErrorHandler.ThrowIfErrorAsync(msg);
string response = await msg.Content.ReadAsStringAsync();
var responseJson = JsonMapper.ToObject(response);
BearerToken = responseJson.GetValue<string>("access_token");
}
}
示例6: HttpPost
public static async void HttpPost(string phone, string password)
{
try
{
HttpClient httpClient = new HttpClient();
string posturi = Config.apiUserRegister;
string date = DateTime.Now.Date.Year.ToString() + "-" + DateTime.Now.Date.Month.ToString() + "-" + DateTime.Now.Date.Day.ToString();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, new Uri(posturi));
HttpFormUrlEncodedContent postData = new HttpFormUrlEncodedContent(
new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("phone", phone),//手机号
new KeyValuePair<string, string>("password", password),//密码
new KeyValuePair<string, string>("date", date),//注册日期
}
);
request.Content = postData;
HttpResponseMessage response = await httpClient.SendRequestAsync(request);
string responseString = await response.Content.ReadAsStringAsync();
JsonObject register = JsonObject.Parse(responseString);
try
{
int code = (int)register.GetNamedNumber("code");
switch (code)
{
case 0:
{
JsonObject user = register.GetNamedObject("user");
Config.UserPhone = user.GetNamedString("phone");
NavigationHelp.NavigateTo(typeof(UserData));
break;
}
case 1:
HelpMethods.Msg("手机号已注册!");
break;
case 2:
HelpMethods.Msg("未知错误!");
break;
default:
break;
}
}
catch (Exception ex)
{
HelpMethods.Msg(ex.Message.ToString());
}
}
catch (Exception ex)
{
HelpMethods.Msg(ex.Message.ToString());
}
}
示例7: SendNotificationAsync
// Post notification
private static async Task SendNotificationAsync(string notificationXML)
{
using (var client = new HttpClient())
{
try
{
var request = new HttpRequestMessage(new HttpMethod("POST"), new Uri("https://login.live.com/accesstoken.srf"));
request.Content = new HttpStringContent(string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=notify.windows.com", Constants.StoreClienId, Constants.StoreClientSecret), Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/x-www-form-urlencoded");
var res = await client.SendRequestAsync(request);
if (res.IsSuccessStatusCode)
{
var tokenJson = await res.Content.ReadAsStringAsync();
var token = JsonConvert.DeserializeObject<Token>(tokenJson);
request = new HttpRequestMessage(new HttpMethod("POST"), new Uri(Constants.OwnerNotificationChannel));
request.Content = new HttpStringContent(notificationXML, Windows.Storage.Streams.UnicodeEncoding.Utf8, "text/xml");
(request.Content as HttpStringContent).Headers.ContentLength = Convert.ToUInt64(notificationXML.Length);
request.Headers.Authorization = new HttpCredentialsHeaderValue(token.TokenType, token.AccessToken);
request.Headers.Add("X-WNS-Type", "wns/toast");
await client.SendRequestAsync(request);
}
}
catch (Exception ex)
{
}
}
}
示例8: SetSessionCookie
public async Task<Tuple<bool, DateTime?>> SetSessionCookie(string login, string password)
{
HttpResponseMessage response = null;
HttpRequestMessage request = null;
using (var httpClient = new HttpClient())
{
request = new HttpRequestMessage(HttpMethod.Post, new Uri(Const.UrlLogin));
request.Content = new HttpFormUrlEncodedContent(new[] {
new KeyValuePair<string, string>("what", "login"),
new KeyValuePair<string, string>("login", login),
new KeyValuePair<string, string>("password", password),
new KeyValuePair<string, string>("persistent", "true"),
});
try
{
response = await httpClient.SendRequestAsync(request);
}
catch (Exception)
{
return new Tuple<bool, DateTime?>(false, null);
}
}
var httpFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
var expireDate = httpFilter.CookieManager.GetCookies(new Uri(Const.UrlFullAddress)).First().Expires ?? DateTime.Now;
return new Tuple<bool, DateTime?>(response.StatusCode == Windows.Web.Http.HttpStatusCode.Ok, expireDate.DateTime);
}
示例9: GetNotifications
public async Task<List<Notification>> GetNotifications()
{
HttpResponseMessage response = null;
HttpRequestMessage request = null;
using (var httpClient = new HttpClient())
{
request = new HttpRequestMessage(HttpMethod.Get, new Uri(Const.UrlNotifyWithTimeStamp));
response = await httpClient.SendRequestAsync(request);
}
var respList = (JObject)JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync());
List<Notification> notList = new List<Notification>();
if (respList.HasValues)
{
var c = respList.First.First;
for (int i = 0; i < c.Count(); i++)
{
var ele = (JProperty)c.ElementAt(i);
Notification n = JsonConvert.DeserializeObject<Notification>(ele.Value.ToString());
n.AddedDate = new DateTime(1970, 1, 1).AddMilliseconds((long)(((JValue)ele.Value["Data"]).Value));
n.PublicationId = ele.Name.Split(':')[0];
n.Id = ele.Name.Split(':')[1];
n.TypeValue = Enum.ParseToNotificationType(((JValue)ele.Value["Type"]).Value.ToString());
notList.Add(n);
}
}
notList = notList.OrderBy(n => n.Status).ThenByDescending(n => n.AddedDate).ToList();
return notList;
}
示例10: receive_file
public override async void receive_file(String devicename, String add, int not)
{
try
{
_httpurl = new Uri(add);
_httpprogress = new Progress<HttpProgress>(ProgressHandler);
HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("GET"), _httpurl);
HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter();
filter.CacheControl.ReadBehavior = HttpCacheReadBehavior.MostRecent;
filter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache;
_httpclient = new HttpClient(filter);
_cancel_token_source = new CancellationTokenSource();
_cancel_token = _cancel_token_source.Token;
scan_network_speed();
_stopwatch.Start();
_httpresponse = await _httpclient.SendRequestAsync(request).AsTask(_cancel_token, _httpprogress);
StorageFolder folder = KnownFolders.PicturesLibrary;
StorageFile file = await folder.CreateFileAsync(this.filepath, CreationCollisionOption.ReplaceExisting);
IRandomAccessStream filestream = await file.OpenAsync(FileAccessMode.ReadWrite);
IOutputStream filewriter = filestream.GetOutputStreamAt(0);
_datawriter = new DataWriter(filewriter);
_timer.Cancel();
_transferspeed /= 1024;
_message = format_message(_stopwatch.Elapsed, "Transferspeed", _transferspeed.ToString(), " kB/s");
this.callback.on_transfer_speed_change(_message, this.results);
this.main_view.text_to_logs(_message.Replace("\t", " "));
_stopwatch.Stop();
_buffer = await _httpresponse.Content.ReadAsBufferAsync();
_datawriter.WriteBuffer(_buffer);
await _datawriter.StoreAsync();
_datawriter.Dispose();
filewriter.Dispose();
filestream.Dispose();
_httpresponse.Content.Dispose();
_httpresponse.Dispose();
_httpclient.Dispose();
_message = format_message(_stopwatch.Elapsed, "File Transfer", "OK", this.filepath);
this.callback.on_file_received(_message, this.results);
this.main_view.text_to_logs(_message.Replace("\t", " "));
}
catch (Exception e)
{
append_error_tolog(e, _stopwatch.Elapsed, "");
}
}
示例11: HttpPost
public static async void HttpPost(string id,string phone,string image, string name, string content, string time,string atName,string atPhone,string atImage)
{
try
{
HttpClient httpClient = new HttpClient();
string posturi = Config.apiCommentPublish;
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, new Uri(posturi));
HttpFormUrlEncodedContent postData = new HttpFormUrlEncodedContent(
new List<KeyValuePair<string, string>>
{
new KeyValuePair<string,string>("id",id),
new KeyValuePair<string,string>("phone",phone),
new KeyValuePair<string, string>("image", image),
new KeyValuePair<string, string>("name", name),
new KeyValuePair<string, string>("content", content),
new KeyValuePair<string, string>("time", time),
new KeyValuePair<string, string>("atName", atName),
new KeyValuePair<string, string>("atPhone", atPhone),
new KeyValuePair<string, string>("atImage", atImage),
}
);
request.Content = postData;
HttpResponseMessage response = await httpClient.SendRequestAsync(request);
}
catch (Exception ex)
{
HelpMethods.Msg(ex.Message.ToString());
}
}
示例12: HttpPost
public static async void HttpPost(string phone, string password)
{
try
{
HttpClient httpClient = new HttpClient();
string posturi = Config.apiUserLogin;
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, new Uri(posturi));
HttpFormUrlEncodedContent postData = new HttpFormUrlEncodedContent(
new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("phone", phone),//手机
new KeyValuePair<string, string>("password", password),//密码
}
);
request.Content = postData;
HttpResponseMessage response = await httpClient.SendRequestAsync(request);
string responseString = await response.Content.ReadAsStringAsync();
Debug.WriteLine(responseString);
JsonObject login = JsonObject.Parse(responseString);
try
{
int code = (int)login.GetNamedNumber("code");
switch (code)
{
case 0:
{
JsonObject user = login.GetNamedObject("user");
Config.UserName = user.GetNamedString("name") ;
Config.UserImage = Config.apiFile + user.GetNamedString("image");
Config.UserPhone = user.GetNamedString("phone") ;
Config.UserDream = user.GetNamedString("dream") ;
Config.UserTag = user.GetNamedString("tag");
NavigationHelp.NavigateTo(typeof(Main));
break;
}
case 1:
HelpMethods.Msg("手机号未注册!");
break;
case 2:
HelpMethods.Msg("密码错误!");
break;
default:
break;
}
}
catch (Exception ex)
{
HelpMethods.Msg("服务器出错!");
Debug.WriteLine(ex.Message.ToString());
}
}
catch (Exception ex)
{
HelpMethods.Msg(ex.Message.ToString());
}
}
示例13: MakeGetCallAsync
public async static Task<HttpResponseMessage> MakeGetCallAsync(HttpRequestMessage message)
{
using (HttpClient client = new HttpClient(new HttpBaseProtocolFilter { AllowAutoRedirect = false }))
{
message.Headers.Add("Authorization", "GoogleLogin auth=" + Auth.getInstance().authToken);
message.Headers.Add("X-Device-ID", "5453EDB5AAC9");
HttpResponseMessage response = await client.SendRequestAsync(message);
return response;
}
}
示例14: SendCreateUserRequestAsync
/// <summary>
/// Sende einen Request an den REST-Server zum Erstellen eines neuen Nutzeraccounts.
/// Bei erfolgreicher Erstellung des Accounts werden die Daten vom Server zurückgeliefert.
/// </summary>
/// <param name="jsonContent">Der JSON String mit den Daten für den Request.</param>
/// <returns>Die Antwort des Servers im JSON Format bei erfolgreichem Request.</returns>
/// <exception cref="APIException">Bei vom Server übermittelten Fehler-Nachricht.</exception>
public async Task<String> SendCreateUserRequestAsync(String jsonContent)
{
// Erstelle einen Http-Request.
HttpClient httpClient = new HttpClient();
// Definiere HTTP-Request Header.
httpClient.DefaultRequestHeaders.Accept.TryParseAdd("application/json");
HttpRequestMessage request = new HttpRequestMessage();
request.Method = HttpMethod.Post;
request.Content = new HttpStringContent(jsonContent, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json");
request.RequestUri = new Uri(BaseURL + "/user");
// Sende den Request und warte auf die Antwort.
HttpResponseMessage response = null;
try
{
response = await httpClient.SendRequestAsync(request);
}
catch (Exception ex)
{
Debug.WriteLine("Exception thrown in SendCreateUserRequest. Message is: " + ex.Message + " and HResult is: " + ex.GetBaseException().HResult);
WebErrorStatus error = WebError.GetStatus(ex.GetBaseException().HResult);
if (WebErrorStatus.ServerUnreachable == error || WebErrorStatus.ServiceUnavailable == error
|| WebErrorStatus.Timeout == error || error == WebErrorStatus.HostNameNotResolved){
Debug.WriteLine("Throwing an APIException with ServerUnreachable.");
// Die Anfrage konnte nicht erfolgreich an den Server übermittelt werden.
throw new APIException(-1, ErrorCodes.ServerUnreachable);
}
if(response == null){
Debug.WriteLine("Cannot continue. Response object is null.");
throw new APIException(-1, ErrorCodes.ServerUnreachable);
}
}
// Lies Antwort aus.
var statusCode = response.StatusCode;
string responseContent = await response.Content.ReadAsStringAsync();
if (statusCode == HttpStatusCode.Created)
{
Debug.WriteLine("Create user request completed successfully.");
Debug.WriteLine("Response from server is: " + responseContent);
}
else
{
// Bilde auf Fehlercode ab und werfe Exception.
mapNonSuccessfulRequestToAPIException(statusCode, responseContent);
}
return responseContent;
}
示例15: GetResponseFromApiByStationNumber
private static async Task<LyonStation> GetResponseFromApiByStationNumber(double stationNumber)
{
var httpClient = new HttpClient();
var msg = new HttpRequestMessage(new HttpMethod("GET"),
new Uri("https://api.jcdecaux.com/vls/v1/stations/" + stationNumber +
"?contract=Lyon&apiKey=8554d38cbccde6f2ca5db7fdd689f1b588ce7786"))
{
Content = new HttpStringContent(string.Empty)
};
msg.Content.Headers.ContentType = new HttpMediaTypeHeaderValue("application/json");
var response = await httpClient.SendRequestAsync(msg).AsTask();
var deserializedResponse = await DeserializeResponseContent(response);
return deserializedResponse;
}