HttpWebRequest.BeginGetRequestStream(AsyncCallback, Object) 메서드

정의

데이터를 쓰는 데 사용할 Stream 개체에 대한 비동기 요청을 시작합니다.

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

매개 변수

callback
AsyncCallback

AsyncCallback 대리자입니다.

state
Object

이 요청에 대한 상태 개체입니다.

반환

비동기 요청을 참조하는 IAsyncResult입니다.

예외

Method 속성이 GET 또는 HEAD인 경우

또는

KeepAlivetrue이고, AllowWriteStreamBufferingfalse이고, ContentLength가 -1이고, SendChunkedfalse이고, Method가 POST 또는 PUT인 경우

스트림이 BeginGetRequestStream(AsyncCallback, Object)에 대한 이전 호출에서 사용되고 있는 경우

또는

TransferEncoding이 값으로 설정되었으며 SendChunkedfalse입니다.

또는

스레드 풀에 스레드가 부족합니다.

요청 캐시 유효성 검사기에서 이 요청에 대한 응답이 캐시에서 제공될 수 있지만 데이터를 쓰는 요청의 경우 캐시를 사용하지 않아야 함을 나타내는 경우. 이 예외는 제대로 구현되지 않은 사용자 지정 캐시 유효성 검사기를 사용하려는 경우에 발생할 수 있습니다.

Abort()가 이전에 호출되었습니다.

.NET Compact Framework 애플리케이션에서 콘텐츠 길이가 0인 요청 스트림을 가져오지 않았으며 올바르게 종료되었습니다. 콘텐츠 길이가 0인 요청을 처리하는 방법에 대한 자세한 내용은 .NET Compact Framework의 네트워크 프로그래밍을 참조하세요.

예제

다음 코드 예제에서는 메서드를 BeginGetRequestStream 사용하여 스트림 instance 대한 비동기 요청을 만듭니다.

#using <System.dll>

using namespace System;
using namespace System::Net;
using namespace System::IO;
using namespace System::Text;
using namespace System::Threading;
ref class HttpWebRequestBeginGetRequest
{
public:
   static ManualResetEvent^ allDone = gcnew ManualResetEvent( false );
   static void Main()
   {
      
      // Create a new HttpWebRequest object.
      HttpWebRequest^ request = dynamic_cast<HttpWebRequest^>(WebRequest::Create( "http://www.contoso.com/example.aspx" ));
      
      // 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.    
      AsyncCallback^ del = gcnew AsyncCallback(GetRequestStreamCallback);
      request->BeginGetRequestStream( del, 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 = dynamic_cast<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.
        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
        AsyncCallback^ del = gcnew AsyncCallback(GetResponseCallback);
        request->BeginGetResponse(del, request);
    }

   static void GetResponseCallback(IAsyncResult^ asynchronousResult)
   {
      HttpWebRequest^ request = dynamic_cast<HttpWebRequest^>(asynchronousResult->AsyncState);

      // End the operation
      HttpWebResponse^ response = dynamic_cast<HttpWebResponse^>(request->EndGetResponse(asynchronousResult));
      Stream^ streamResponse = response->GetResponseStream();
      StreamReader^ streamRead = gcnew StreamReader(streamResponse);
      String^ responseString = streamRead->ReadToEnd();
      Console::WriteLine(responseString);
      // Close the stream object
      streamResponse->Close();
      streamRead->Close();

      // Release the HttpWebResponse
      response->Close();
      allDone->Set();
   }
};

void main()
{
   HttpWebRequestBeginGetRequest::Main();
}
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

설명

메서드는 BeginGetRequestStream 에 대한 데이터를 HttpWebRequest보내는 데 사용되는 스트림에 대한 비동기 요청을 시작합니다. 비동기 콜백 메서드는 메서드를 EndGetRequestStream 사용하여 실제 스트림을 반환합니다.

메서드는 BeginGetRequestStream 이 메서드가 비동기화되기 전에 일부 동기 설정 작업(예: DNS 확인, 프록시 검색 및 TCP 소켓 연결)을 완료해야 합니다. 따라서 오류에 대한 예외가 throw되거나 메서드가 성공하기 전에 초기 동기 설정 작업을 완료하는 데 상당한 시간(네트워크 설정에 따라 최대 몇 분)이 걸릴 수 있으므로 UI(사용자 인터페이스) 스레드에서 이 메서드를 호출해서는 안 됩니다.

스레드 풀에 대한 자세한 내용은 관리되는 스레드 풀을 참조하세요.

참고

애플리케이션 특정 요청에 대 한 동기 및 비동기 메서드를 혼합할 수 없습니다. 메서드를 호출하는 BeginGetRequestStream 경우 메서드를 BeginGetResponse 사용하여 응답을 검색해야 합니다.

참고

애플리케이션에 네트워크 추적을 사용하도록 설정하면 이 멤버에서 추적 정보를 출력합니다. 자세한 내용은 .NET Framework 네트워크 추적을 참조하세요.

적용 대상

추가 정보