本文整理汇总了C#中System.Net.HttpWebRequest.GetRequestStreamAsync方法的典型用法代码示例。如果您正苦于以下问题:C# HttpWebRequest.GetRequestStreamAsync方法的具体用法?C# HttpWebRequest.GetRequestStreamAsync怎么用?C# HttpWebRequest.GetRequestStreamAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.HttpWebRequest
的用法示例。
在下文中一共展示了HttpWebRequest.GetRequestStreamAsync方法的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: 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;
}
}
示例3: GetUploadStreamAsync
public Task<Stream> GetUploadStreamAsync()
{
request = (HttpWebRequest)WebRequest.Create("https://secure.nicovideo.jp/secure/login");
request.Method = ContentMethod.Post;
request.ContentType = ContentType.Form;
request.CookieContainer = cookieContainer;
return request.GetRequestStreamAsync();
}
示例4: GetUploadStreamAsync
public Task<Stream> GetUploadStreamAsync()
{
request = (HttpWebRequest)WebRequest.Create(
"http://www.nicovideo.jp/tag_edit/" + id);
request.Method = ContentMethod.Post;
request.CookieContainer = cookieContainer;
request.ContentType = ContentType.Form;
return request.GetRequestStreamAsync();
}
示例5: RegisterExternal
public async Task RegisterExternal(
string username)
{
string uri = String.Format("{0}/api/Account/RegisterExternal", BaseUri);
RegisterExternalBindingModel model = new RegisterExternalBindingModel
{
UserName = username
};
HttpWebRequest request = new HttpWebRequest(new Uri(uri));
request.ContentType = "application/json";
request.Accept = "application/json";
request.Headers.Add("Authorization", String.Format("Bearer {0}", AccessToken));
request.Method = "POST";
string postJson = JsonConvert.SerializeObject(model);
byte[] bytes = Encoding.UTF8.GetBytes(postJson);
using (Stream requestStream = await request.GetRequestStreamAsync())
{
requestStream.Write(bytes, 0, bytes.Length);
}
try
{
WebResponse response = await request.GetResponseAsync();
HttpWebResponse httpResponse = (HttpWebResponse)response;
string result;
using (Stream responseStream = httpResponse.GetResponseStream())
{
result = new StreamReader(responseStream).ReadToEnd();
Console.WriteLine(result);
}
}
catch (SecurityException)
{
throw;
}
catch (Exception ex)
{
throw new InvalidOperationException("Unable to register user", ex);
}
}
示例6: GetHttpPostResponse
public async Task<String> GetHttpPostResponse(HttpWebRequest request, string postData)
{
Received = null;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
var requestBody = Encoding.UTF8.GetBytes(postData);
// ASYNC: using awaitable wrapper to get request stream
using (var postStream = await request.GetRequestStreamAsync())
{
// Write to the request stream.
// ASYNC: writing to the POST stream can be slow
await postStream.WriteAsync(requestBody, 0, requestBody.Length);
}
try
{
// ASYNC: using awaitable wrapper to get response
var response = (HttpWebResponse) await request.GetResponseAsync();
if (response != null)
{
var reader = new StreamReader(response.GetResponseStream());
// ASYNC: using StreamReader's async method to read to end, in case
// the stream i slarge.
Received = await reader.ReadToEndAsync();
}
}
catch (WebException we)
{
var reader = new StreamReader(we.Response.GetResponseStream());
var responseString = reader.ReadToEnd();
Debug.WriteLine(responseString);
return responseString;
}
return Received;
}
示例7: DownloadStringAsync
public async Task<string> DownloadStringAsync(HttpWebRequest request, byte[] postData)
{
request.UserAgent = SKore.ChromeAgent;
request.AllowAutoRedirect = false;
request.CookieContainer = Cookies;
request.Method = "GET";
request.Proxy = Proxy;
if (postData != null)
{
request.Method = "POST";
request.ContentLength = postData.Length;
using (var reqStream = await request
.GetRequestStreamAsync().ConfigureAwait(false))
{
await reqStream.WriteAsync(postData,
0, postData.Length).ConfigureAwait(false);
}
}
return (await VerifyResponseBody(
request).ConfigureAwait(false));
}
示例8: getRequestStreamAsync
private static Task<Stream> getRequestStreamAsync(HttpWebRequest request)
{
return request.GetRequestStreamAsync();
}
示例9: ConfigureRequest
private async Task ConfigureRequest(HttpWebRequest request, IEnumerable<FileInfo> files)
{
Debug.Assert(request != null);
Debug.Assert(files != null);
using (Stream memStream = new MemoryStream())
{
string boundary = "-----------------------" + DateTime.Now.Ticks.ToString("x");
request.Accept = "*/*";
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.KeepAlive = true;
var boundaryBytesMiddle = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
var boundaryBytesLast = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
await memStream.WriteAsync(boundaryBytesMiddle, 0, boundaryBytesMiddle.Length);
var headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
var count = files.Count();
Debug.WriteLine("--->Adding {0} files to request.", files.Count());
foreach (var file in files)
{
Debug.WriteLine("--->Adding file ({0}) to request.", file.FullName);
var headerContentType = (file.Extension == ".cer") ? "application/x-x509-ca-cert" : "application/x-zip-compressed";
var header = string.Format(headerTemplate, file.Name, file.Name, headerContentType);
var headerBytes = Encoding.UTF8.GetBytes(header);
await memStream.WriteAsync(headerBytes, 0, headerBytes.Length);
using (var fileStream = file.OpenRead())
{
await fileStream.CopyToAsync(memStream);
if (--count > 0)
{
Debug.WriteLine("--->Padding memstream.");
await memStream.WriteAsync(boundaryBytesMiddle, 0, boundaryBytesMiddle.Length);
Debug.WriteLine("--->Padded memstream.");
}
else
{
Debug.WriteLine("--->Padding memstream (last time).");
await memStream.WriteAsync(boundaryBytesLast, 0, boundaryBytesLast.Length);
Debug.WriteLine("--->Padded memstream (last time).");
}
}
}
Debug.WriteLine("--->Added files to request.");
request.ContentLength = memStream.Length;
Debug.WriteLine("--->Getting request stream.", files.Count());
using (Stream requestStream = await request.GetRequestStreamAsync())
{
Debug.WriteLine("--->Copying memstream to requestStream");
memStream.Position = 0;
await memStream.CopyToAsync(requestStream);
Debug.WriteLine("--->Copyied memstream to requestStream");
}
}
}
示例10: SendNextChunkAsync
private async Task<ChunkStatus> SendNextChunkAsync(Stream blobStream, int chunkSize, long chunkStart, long bytesTotal) {
// Errors will be caught by the caller.
var buffer = new byte[chunkSize];
int bytesTransferred = await blobStream.ReadAsync(buffer, 0, chunkSize);
this.request = WebRequestCreator.BrowserHttp.Create(uri) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/octet-stream"; // default
request.ContentLength = bytesTransferred;
// Set headers
foreach (var entry in this.headers) {
request.Headers[entry.Key] = entry.Value;
}
if (headerAccept != null) request.Accept = headerAccept;
if (headerContentType != null) request.ContentType = headerContentType;
// Set content-range, specially
if (headerContentRange != null) {
request.Headers["X-MSHACK-Content-Range"] = "" + chunkStart + "-" + (chunkStart + bytesTransferred - 1) + "/" + bytesTotal;
}
using (Stream sendStream = await request.GetRequestStreamAsync()) {
await sendStream.WriteAsync(buffer, 0, bytesTransferred);
}
HttpStatusCode status;
WebHeaderCollection headers;
string body;
using (HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse)
using (Stream responseStream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(responseStream)) {
status = response.StatusCode;
headers = response.GetRealOrFakeHeaders();
body = await reader.ReadToEndAsync();
}
CompletedEventArgs args = new CompletedEventArgs(status, headers, body);
return new ChunkStatus(bytesTransferred, args);
}
示例11: PostStringAsync
public async Task PostStringAsync(string url, string bodyParameter)
{
string info = string.Empty;
req = HttpWebRequest.CreateHttp(url);
req.Method = "POST";
WebResponse res = null;
try
{
using (Stream stream = await req.GetRequestStreamAsync())
{
byte[] buffer = Encoding.UTF8.GetBytes(bodyParameter);
await stream.WriteAsync(buffer, 0, buffer.Length);
await stream.FlushAsync();
}
}
catch (Exception e)
{
OnGetDataEvent(new ProgressEventArgs
{
DownLoadData = null,
ExceptionInfo = e.Message,
IsComplete = false,
IsException = true
});
return;
}
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;
}
}
示例12: GetRequestStreamAsync
public Task<Stream> GetRequestStreamAsync(HttpWebRequest request)
{
return request.GetRequestStreamAsync();
}
示例13: CallHttpWithBodyAsync
private Task<Response> CallHttpWithBodyAsync(HttpWebRequest request, byte[] body)
{
try
{
return Task.Run<Response>(async () =>
{
var requestStream = await request.GetRequestStreamAsync();
requestStream.Write(body, 0, body.Length);
var response = (HttpWebResponse)await request.GetResponseAsync();
var streamResponse = response.GetResponseStream();
return new Response() { ResponseStream = streamResponse, StatusCode = response.StatusCode };
});
}
catch
{
throw;
}
}
示例14: RequestAsync
/// <summary>
/// Asynchronously performs an HttpWebRequest with request data.
/// </summary>
/// <param name="request">Required. The HttpWebRequest to represent the base request.</param>
/// <param name="contentType">Required. The Content-Type HTTP header to send with the request.</param>
/// <param name="data">Required. A byte array representing the request data to send with the request.</param>
/// <param name="cancellationToken">Optional. The token to monitor for cancellation requests.</param>
/// <param name="progressHandler">Optional. The event handler to invoke when progress has changed.</param>
/// <param name="completeHandler">Optional. The event handler to invoke when the request has finished.</param>
/// <returns>Returns a HttpWebResponse representing the response from the server.</returns>
public async Task<HttpWebResponse> RequestAsync(HttpWebRequest request, string contentType, byte[] data,
CancellationToken cancellationToken = default(CancellationToken), TaskProgressEventHandler progressHandler = null, TaskCompleteEventHandler completeHandler = null)
{
request.ContentLength = (data != null) ? data.Length : 0;
if (!String.IsNullOrEmpty(contentType))
request.ContentType = contentType;
// Write to request stream
using (Stream requestStream = await request.GetRequestStreamAsync())
{
int bufferSize = GetOptimalBufferSize(data.Length);
int bytesDone = new int();
while (bytesDone < data.Length)
{
// ProgressHandler: Begin asynchronous invoke
IAsyncResult progressHandlerResult = null;
if (progressHandler != null)
progressHandlerResult = progressHandler.BeginInvoke(Math.Min(1.0, (double)bytesDone / (double)data.Length), null, null);
// WriteTask: Start writing to stream asynchronously
int nextChunkSize = Math.Min(data.Length - bytesDone, bufferSize);
Task writeTask = requestStream.WriteAsync(data, bytesDone, nextChunkSize, cancellationToken);
// End asynchronous ProgressHandler
if (progressHandler != null && progressHandlerResult != null)
progressHandler.EndInvoke(progressHandlerResult);
// WriteTask: Wait for chunk upload to finish
await writeTask;
bytesDone += nextChunkSize;
}
}
HttpWebResponse result;
{
// HttpWebResponse: Start task
Task<WebResponse> resultTask = request.GetResponseAsync();
// CompleteHandler: Begin asynchronous invoke
IAsyncResult completeHandlerResult = null;
if (completeHandler != null)
completeHandler.BeginInvoke(null, null);
// HttpWebResponse: Await result
result = (HttpWebResponse)(await resultTask);
// CompleteHandler: End asynchronous invoke
if (completeHandler != null && completeHandlerResult != null)
completeHandler.EndInvoke(completeHandlerResult);
}
return result;
}
示例15: Write
public async virtual void Write(OAuthMessage message, HttpWebRequest request)
{
if (message == null)
{
throw new ArgumentNullException("message");
}
if (request == null)
{
throw new ArgumentNullException("request");
}
request.Method = this.GetHttpMethod(message);
request.ContentType = this.GetHttpContentType(message);
this.Write(message, await request.GetRequestStreamAsync());
}