HttpWebRequest.GetRequestStream : What it does?

后端 未结 2 1307
耶瑟儿~
耶瑟儿~ 2021-01-30 11:12

Code exemple:

HttpWebRequest request =
   (HttpWebRequest)HttpWebRequest.Create(\"http://some.existing.url\");

request.Method = \"POST\";
request.ContentType          


        
2条回答
  •  日久生厌
    2021-01-30 11:20

    You use GetRequestStream() to synchronously obtain a reference to the upload stream. It is only after you have finished writing to the stream that the actual request is send.

    However, I would suggest that you use the BeginGetRequestStream method instead of GetRequestStream. BeginGetRequestStream performs asynchronously and don't lock the current thread while the stream is being obtained. You pass a callback and a context to the BeginGetRequestStream. In the callback, you can call EndGetRequestStream() to finally grab a reference and repeat the writing steps listed above (for synchronous behavior). Example:

    context.Request.BeginGetRequestStream(new AsyncCallback(Foo), context);
    
    public void Foo(IAsyncResult asyncResult)
        {
            Context context = (Context)asyncResult.AsyncState;
            try
            {
                HttpWebRequest request = context.Request;
    
                using (var requestStream = request.EndGetRequestStream(asyncResult))
                using (var writer = new StreamWriter(requestStream))
                {
                    // write to the request stream
                }
    
                request.BeginGetResponse(new AsyncCallback(ProcessResponse), context);
            }
    

    Be very careful with BeginGetRequestStream. It never times out, thus you must add additional logic to your program to recover from situations where GetRequestStream will throw a timeout exception.

    In general, threads are cheap. The async Begin/End methods of HttpWebRequest are only worth using if you will have 10,000 or more concurrent requests; because implementing timeouts is very tricky and error-prone. In general, using BeginGetRequestStream is premature optimization unless you need significant performance gains.

提交回复
热议问题