本文整理汇总了C#中System.Net.HttpWebRequest.GetResponseAsync方法的典型用法代码示例。如果您正苦于以下问题:C# HttpWebRequest.GetResponseAsync方法的具体用法?C# HttpWebRequest.GetResponseAsync怎么用?C# HttpWebRequest.GetResponseAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.HttpWebRequest
的用法示例。
在下文中一共展示了HttpWebRequest.GetResponseAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Login
public async Task<string> Login(string username, string password)
{
HttpWebRequest request = new HttpWebRequest(new Uri(String.Format("{0}Token", Constants.BaseAddress)));
request.Method = "POST";
string postString = String.Format("username={0}&password={1}&grant_type=password", HttpUtility.HtmlEncode(username), HttpUtility.HtmlEncode(password));
byte[] bytes = Encoding.UTF8.GetBytes(postString);
using (Stream requestStream = await request.GetRequestStreamAsync())
{
requestStream.Write(bytes, 0, bytes.Length);
}
try
{
HttpWebResponse httpResponse = (HttpWebResponse)(await request.GetResponseAsync());
string json;
using (Stream responseStream = httpResponse.GetResponseStream())
{
json = new StreamReader(responseStream).ReadToEnd();
}
TokenResponseModel tokenResponse = JsonConvert.DeserializeObject<TokenResponseModel>(json);
return tokenResponse.AccessToken;
}
catch (Exception ex)
{
throw new SecurityException("Bad credentials", ex);
}
}
示例2: GetExternalLoginProviders
public async Task<IEnumerable<ExternalLoginViewModel>> GetExternalLoginProviders()
{
string uri = String.Format("{0}/api/Account/ExternalLogins?returnUrl=%2F&generateState=true", _baseUri);
HttpWebRequest request = new HttpWebRequest(new Uri(uri));
request.Method = "GET";
try
{
WebResponse response = await request.GetResponseAsync();
HttpWebResponse httpResponse = (HttpWebResponse) response;
string result;
using (Stream responseStream = httpResponse.GetResponseStream())
{
result = new StreamReader(responseStream).ReadToEnd();
}
List<ExternalLoginViewModel> models = JsonConvert.DeserializeObject<List<ExternalLoginViewModel>>(result);
return models;
}
catch (SecurityException)
{
throw;
}
catch (Exception ex)
{
throw new InvalidOperationException("Unable to get login providers", ex);
}
}
示例3: Register
public async Task<bool> Register(string username, string password, string confirmPassword)
{
RegisterModel model = new RegisterModel
{
ConfirmPassword = confirmPassword,
Password = password,
UserName = username
};
HttpWebRequest request = new HttpWebRequest(new Uri(String.Format("{0}api/Account/Register", Constants.BaseAddress)));
request.Method = "POST";
request.ContentType = "application/json";
request.Accept = "application/json";
string json = JsonConvert.SerializeObject(model);
byte[] bytes = Encoding.UTF8.GetBytes(json);
using(Stream stream = await request.GetRequestStreamAsync())
{
stream.Write(bytes, 0, bytes.Length);
}
try
{
await request.GetResponseAsync();
return true;
}
catch (Exception)
{
return false;
}
}
示例4: SendAsync
/// <summary>
/// Queues a web request into our queue and returns an awaitable task.
/// </summary>
public static Task<XDocument> SendAsync(HttpWebRequest request)
{
lock (instance)
{
instance.currentTask = instance.currentTask.ContinueWith(async previousTask =>
{
var response = await request.GetResponseAsync();
var responseStream = response.GetResponseStream();
XDocument doc = null;
using (var streamReader = new StreamReader(responseStream))
{
string xml = await streamReader.ReadToEndAsync();
doc = XDocument.Parse(xml);
}
// Wait a bit to throttle the requests:
await Task.Delay(50);
return doc;
}).Unwrap();
return instance.currentTask;
}
}
示例5: ConnectAsync
public async Task<WebSocket> ConnectAsync(HttpWebRequest request, CancellationToken cancellationToken) {
HttpWebResponse response;
using (cancellationToken.Register(request.Abort)) {
response = (HttpWebResponse)await request.GetResponseAsync();
}
InspectResponse?.Invoke(response);
// TODO: Validate handshake
HttpStatusCode statusCode = response.StatusCode;
if (statusCode != HttpStatusCode.SwitchingProtocols) {
response.Dispose();
throw new InvalidOperationException("Incomplete handshake, invalid status code: " + statusCode);
}
// TODO: Validate Sec-WebSocket-Key/Sec-WebSocket-Accept
string subProtocol = response.Headers[Constants.Headers.SecWebSocketProtocol];
if (!string.IsNullOrEmpty(subProtocol) && !SubProtocols.Contains(subProtocol, StringComparer.OrdinalIgnoreCase)) {
throw new InvalidOperationException("Incomplete handshake, the server specified an unknown sub-protocol: " + subProtocol);
}
var stream = response.GetResponseStream();
return CommonWebSocket.CreateClientWebSocket(stream, subProtocol, KeepAliveInterval, ReceiveBufferSize, UseZeroMask);
}
示例6: ProcessResponse
private static async Task<RESTResponse> ProcessResponse(HttpWebRequest request)
{
RESTResponse result = new RESTResponse();
try
{
using (HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse)
{
result.StatusCode = (int)response.StatusCode;
using (Stream stream = response.GetResponseStream())
{
result.Content = new StreamReader(stream, System.Text.Encoding.UTF8).ReadToEnd();
}
}
}
catch (WebException ex)
{
if ((ex.Status == WebExceptionStatus.ProtocolError) && (ex.Response != null))
{
HttpWebResponse response = ex.Response as HttpWebResponse;
result.StatusCode = (int)response.StatusCode;
using (Stream stream = response.GetResponseStream())
{
result.Content = new StreamReader(stream, System.Text.Encoding.UTF8).ReadToEnd();
}
}
}
return result;
}
示例7: ExecuteRequestAsync
public async Task<JToken> ExecuteRequestAsync(HttpWebRequest request)
{
EnforceRateLimit();
var response = await request.GetResponseAsync();
var result = await GetResponseStringAsync(response.GetResponseStream());
return ExecuteRequestBase(result);
}
示例8: GetResponseStringFromRequest
private static async Task<string> GetResponseStringFromRequest(HttpWebRequest request)
{
try
{
using (var response = await request.GetResponseAsync()
.ConfigureAwait(false))
{
return GetResponseString(response);
}
}
catch (WebException e)
{
using (var response = e.Response.GetResponseStream())
{
if (response == null)
{
throw;
}
JObject responseItem;
try
{
responseItem = JObject.Load(new JsonTextReader(new StreamReader(response)));
}
catch (Exception)
{
throw e;
}
ThrowIfIsException(responseItem);
throw;
}
}
}
示例9: readResponse
private static async Task<string> readResponse(HttpWebRequest rq, string expectedContentType)
{
HttpWebResponse rsp;
try
{
rsp = (HttpWebResponse)await rq.GetResponseAsync();
}
catch (WebException wex)
{
rsp = (HttpWebResponse)wex.Response;
}
if (rsp.StatusCode != HttpStatusCode.OK) Console.Error.WriteLine(rsp.StatusCode.ToString());
string[] contentType = rsp.ContentType.Split(new string[1] { "; " }, StringSplitOptions.None);
if (contentType[0] != expectedContentType) Console.Error.WriteLine("Received Content-Type '{0}', expected '{1}'", contentType[0], expectedContentType);
using (var st = rsp.GetResponseStream())
using (var tr = new StreamReader(st, Encoding.UTF8))
{
string rspstr = await tr.ReadToEndAsync();
if (displayResponse)
{
Console.Out.WriteLineAsync(rspstr);
}
return rspstr;
}
}
示例10: GetStringAsync
/// <summary>
/// GET请求
/// </summary>
/// <param name="url" "传入的url地址"></param>
/// <returns></returns>
public async Task GetStringAsync(string url)
{
string info = string.Empty;
req = WebRequest.CreateHttp(url);
req.Method = "GET";
WebResponse res = null;
req.ContinueTimeout = 1000;
try
{
res = await req.GetResponseAsync();
}
catch (Exception e)
{
OnGetDataEvent(new ProgressEventArgs
{
DownLoadData = null,
ExceptionInfo = e.Message,
IsComplete = false,
IsException = true
});
return;
}
//如果返回数据
if (req.HaveResponse && null != res)
{
using (Stream stream = res.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream))
{
info = await reader.ReadToEndAsync();
}
}
//通知注册的事件完成下载
OnGetDataEvent(new ProgressEventArgs
{
DownLoadData = info,
ExceptionInfo = null,
IsComplete = true,
IsException = false
});
}
else
{
//没有数据
OnGetDataEvent(new ProgressEventArgs
{
DownLoadData = null,
ExceptionInfo = null,
IsComplete = false,
IsException = true
});
return;
}
}
示例11: GetResponseAsync
public Task<WebResponse> GetResponseAsync(HttpWebRequest request, int timeoutMs)
{
if (timeoutMs > 0)
{
return GetResponseAsync(request, TimeSpan.FromMilliseconds(timeoutMs));
}
return request.GetResponseAsync();
}
示例12: CreateResponse
static HttpWebResponse CreateResponse(HttpWebRequest request)
{
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)(request.GetResponseAsync().Result);
}
catch { }
return response;
}
示例13: GetDownloadStreamAsync
public Task<WebResponse> GetDownloadStreamAsync()
{
request = (HttpWebRequest)WebRequest.Create(
"http://www.nicovideo.jp/api/watch/mylistvideo?id=" + id);
request.Method = ContentMethod.Get;
request.CookieContainer = cookieContainer;
return request.GetResponseAsync();
}
示例14: GetRequestStreamCallback
private async Task GetRequestStreamCallback(Task<Stream> task, HttpWebRequest request)
{
Stream postStream = await task.ConfigureAwait(false);
this.WriteMultipartObject(postStream, this.Parameters);
postStream.Close();
var responseTask = request.GetResponseAsync();
await GetResponseCallback(responseTask);
}
示例15: _getApiResponseAsync
private async Task<string> _getApiResponseAsync(HttpWebRequest request)
{
using (var response = await request.GetResponseAsync())
{
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
return streamReader.ReadToEnd();
}
}
}