HttpWebRequest.BeginGetRequestStream(AsyncCallback, Object) Metodo
Definizione
Importante
Alcune informazioni sono relative alla release non definitiva del prodotto, che potrebbe subire modifiche significative prima della release definitiva. Microsoft non riconosce alcuna garanzia, espressa o implicita, in merito alle informazioni qui fornite.
Avvia una richiesta asincrona per un Stream oggetto da utilizzare per scrivere dati.
public:
override IAsyncResult ^ BeginGetRequestStream(AsyncCallback ^ callback, System::Object ^ state);
public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state);
public override IAsyncResult BeginGetRequestStream(AsyncCallback? callback, object? state);
override this.BeginGetRequestStream : AsyncCallback * obj -> IAsyncResult
Public Overrides Function BeginGetRequestStream (callback As AsyncCallback, state As Object) As IAsyncResult
Parametri
- callback
- AsyncCallback
Delegato AsyncCallback .
- state
- Object
Oggetto stato per questa richiesta.
Valori restituiti
Oggetto IAsyncResult che fa riferimento alla richiesta asincrona.
Eccezioni
La Method proprietà è GET o HEAD.
-o-
KeepAliveè , true è AllowWriteStreamBufferingfalse, ContentLength è -1, SendChunked è falsee Method è POST o PUT.
Il flusso viene usato da una chiamata precedente a BeginGetRequestStream(AsyncCallback, Object)
-o-
TransferEncoding è impostato su un valore e SendChunked è false.
-o-
Il pool di thread sta esaurendo i thread.
Il validator della cache delle richieste ha indicato che la risposta per questa richiesta può essere servita dalla cache; Tuttavia, le richieste che scrivono dati non devono usare la cache. Questa eccezione può verificarsi se si usa un validator di cache personalizzato implementato in modo non corretto.
Abort() è stato chiamato in precedenza.
In un'applicazione .NET Compact Framework, un flusso di richiesta con lunghezza zero del contenuto non è stato ottenuto e chiuso correttamente.
Esempio
Nell'esempio di codice seguente viene usato il BeginGetRequestStream metodo per effettuare una richiesta asincrona per un'istanza del flusso.
using System;
using System.Net;
using System.IO;
using System.Text;
using System.Threading;
class HttpWebRequestBeginGetRequest
{
private static ManualResetEvent allDone = new ManualResetEvent(false);
public static void Main(string[] args)
{
// Create a new HttpWebRequest object.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.contoso.com/example.aspx");
request.ContentType = "application/x-www-form-urlencoded";
// Set the Method property to 'POST' to post data to the URI.
request.Method = "POST";
// start the asynchronous operation
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
// Keep the main thread from continuing while the asynchronous
// operation completes. A real world application
// could do something useful such as updating its user interface.
allDone.WaitOne();
}
private static void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
Stream postStream = request.EndGetRequestStream(asynchronousResult);
Console.WriteLine("Please enter the input data to be posted:");
string postData = Console.ReadLine();
// Convert the string into a byte array.
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Write to the request stream.
postStream.Write(byteArray, 0, postData.Length);
postStream.Close();
// Start the asynchronous operation to get the response
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
private static void GetResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
Console.WriteLine(responseString);
// Close the stream object
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse
response.Close();
allDone.Set();
}
}
Imports System.Net
Imports System.IO
Imports System.Text
Imports System.Threading
Class HttpWebRequestBeginGetRequest
Public Shared allDone As New ManualResetEvent(False)
Shared Sub Main()
' Create a new HttpWebRequest object.
Dim request As HttpWebRequest = CType(WebRequest.Create("http://www.contoso.com/example.aspx"), _
HttpWebRequest)
' Set the ContentType property.
request.ContentType = "application/x-www-form-urlencoded"
' Set the Method property to 'POST' to post data to the URI.
request.Method = "POST"
' Start the asynchronous operation.
Dim result As IAsyncResult = _
CType(request.BeginGetRequestStream(AddressOf GetRequestStreamCallback, request), _
IAsyncResult)
' Keep the main thread from continuing while the asynchronous
' operation completes. A real world application
' could do something useful such as updating its user interface.
allDone.WaitOne()
End Sub
Private Shared Sub GetRequestStreamCallback(ByVal asynchronousResult As IAsyncResult)
Dim request As HttpWebRequest = CType(asynchronousResult.AsyncState, HttpWebRequest)
' End the operation
Dim postStream As Stream = request.EndGetRequestStream(asynchronousResult)
Console.WriteLine("Please enter the input data to be posted:")
Dim postData As [String] = Console.ReadLine()
' Convert the string into byte array.
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
' Write to the stream.
postStream.Write(byteArray, 0, postData.Length)
postStream.Close()
' Start the asynchronous operation to get the response
Dim result As IAsyncResult = _
CType(request.BeginGetResponse(AddressOf GetResponseCallback, request), _
IAsyncResult)
End Sub
Private Shared Sub GetResponseCallback(ByVal asynchronousResult As IAsyncResult)
Dim request As HttpWebRequest = CType(asynchronousResult.AsyncState, HttpWebRequest)
' Get the response.
Dim response As HttpWebResponse = CType(request.EndGetResponse(asynchronousResult), _
HttpWebResponse)
Dim streamResponse As Stream = response.GetResponseStream()
Dim streamRead As New StreamReader(streamResponse)
Dim responseString As String = streamRead.ReadToEnd()
Console.WriteLine(responseString)
' Close Stream object.
streamResponse.Close()
streamRead.Close()
' Release the HttpWebResponse.
allDone.Set()
response.Close()
End Sub
End Class
Commenti
Cautela
WebRequest
HttpWebRequest, ServicePoint, e WebClient sono obsoleti e non è consigliabile usarli per il nuovo sviluppo. Utilizzare invece HttpClient.
Il BeginGetRequestStream metodo avvia una richiesta asincrona per un flusso usato per inviare dati per .HttpWebRequest Il metodo di callback asincrono usa il EndGetRequestStream metodo per restituire il flusso effettivo.
Il BeginGetRequestStream metodo richiede il completamento di alcune attività di installazione sincrone (risoluzione DNS, rilevamento proxy e connessione socket TCP, ad esempio) prima che questo metodo diventi asincrono. Di conseguenza, questo metodo non deve mai essere chiamato su un thread dell'interfaccia utente perché potrebbe richiedere molto tempo (fino a diversi minuti a seconda delle impostazioni di rete) per completare le attività di installazione sincrone iniziali prima che venga generata un'eccezione per un errore o il metodo abbia esito positivo.
Per altre informazioni sul pool di thread, vedere Pool di thread gestiti.
Nota
L'applicazione non può combinare metodi sincroni e asincroni per una determinata richiesta. Se si chiama il BeginGetRequestStream metodo , è necessario usare il BeginGetResponse metodo per recuperare la risposta.
Nota
Questo membro restituisce informazioni di traccia quando si abilita la traccia di rete nell'applicazione. Per altre informazioni, vedere Network Tracing in the .NET Framework.