本文整理汇总了C#中System.Net.HttpWebRequest.EndGetResponse方法的典型用法代码示例。如果您正苦于以下问题:C# HttpWebRequest.EndGetResponse方法的具体用法?C# HttpWebRequest.EndGetResponse怎么用?C# HttpWebRequest.EndGetResponse使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.HttpWebRequest
的用法示例。
在下文中一共展示了HttpWebRequest.EndGetResponse方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetResponseAsync
public Task<WebResponse> GetResponseAsync(HttpWebRequest request, int timeoutMs)
{
if (timeoutMs > 0)
{
return GetResponseAsync(request, TimeSpan.FromMilliseconds(timeoutMs));
}
var tcs = new TaskCompletionSource<WebResponse>();
try
{
request.BeginGetResponse(iar =>
{
try
{
var response = (HttpWebResponse)request.EndGetResponse(iar);
tcs.SetResult(response);
}
catch (Exception exc)
{
tcs.SetException(exc);
}
}, null);
}
catch (Exception exc)
{
tcs.SetException(exc);
}
return tcs.Task;
}
示例2: AsyncGetResponse
/// <summary>
/// Encapsulates GetResponse so tests don't invoke the request
/// </summary>
/// <param name="req">Request to Twitter</param>
/// <returns>Response to Twitter</returns>
public static HttpWebResponse AsyncGetResponse(HttpWebRequest req)
{
Exception asyncException = null;
var resetEvent = new ManualResetEvent(/*initialStateSignaled:*/ false);
HttpWebResponse res = null;
req.BeginGetResponse(
new AsyncCallback(
ar =>
{
try
{
res = req.EndGetResponse(ar) as HttpWebResponse;
}
catch (Exception ex)
{
asyncException = ex;
}
finally
{
resetEvent.Set();
}
}), null);
resetEvent.WaitOne();
if (asyncException != null)
{
throw asyncException;
}
return res;
}
示例3: HttpGetStreamCallback
public void HttpGetStreamCallback(IAsyncResult asynchronousResult, HttpWebRequest request)
{
try{
// End the operation
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
if (response.StatusCode != HttpStatusCode.OK)
{
getAsyncSendFailResult();
return;
}
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
String responseData = streamRead.ReadToEnd();
getConnectionReceivedHandler(responseData);
streamResponse.Close();
streamRead.Close();
response.Close();
}
catch (Exception e)
{
log.errorCause( "http get failed ", e);
getAsyncSendFailResult();
}
}
示例4: GetResponseAsynch
private HttpWebResponse GetResponseAsynch(HttpWebRequest request)
{
return AsynchHelper.WaitForAsynchResponse(
c => request.BeginGetResponse(c, null),
(r, s) => (HttpWebResponse)request.EndGetResponse(r)
);
}
示例5: receiveHttpResonse
public async Task<string> receiveHttpResonse(HttpWebRequest request, IAsyncResult asynchronousResult)
{
string responseString = String.Empty;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
responseString = await streamRead.ReadToEndAsync();
//var userResp = JsonConvert.DeserializeObject<T>(responseString);
// Close the stream object
streamRead.Close();
streamResponse.Close();
// Release the HttpWebResponse
response.Close();
HttpStatusCode responseCode = response.StatusCode;
if (responseCode == HttpStatusCode.Created)
{
return Constants.SUCCESS;
}
else
{
return Constants.ERROR;
}
}
示例6: IssueRequest
public static IEnumerator<object> IssueRequest(HttpWebRequest request)
{
var fResponse = new Future<HttpWebResponse>();
ThreadPool.QueueUserWorkItem(
(__) => {
try {
request.BeginGetResponse(
(ar) => {
try {
var _ = (HttpWebResponse)request.EndGetResponse(ar);
fResponse.SetResult(_, null);
} catch (Exception ex) {
fResponse.SetResult(null, ex);
}
}, null
);
} catch (Exception ex_) {
fResponse.SetResult(null, ex_);
}
}
);
yield return fResponse;
if (fResponse.Failed)
throw new RequestFailedException(fResponse.Error);
using (var response = fResponse.Result) {
var fResponseStream = Future.RunInThread(
() => response.GetResponseStream()
);
yield return fResponseStream;
Encoding encoding = AsyncTextReader.DefaultEncoding;
if (!string.IsNullOrEmpty(response.CharacterSet))
encoding = Encoding.GetEncoding(response.CharacterSet);
string responseText;
using (var stream = fResponseStream.Result)
using (var adapter = new AsyncTextReader(new StreamDataAdapter(stream, false), encoding)) {
var fText = adapter.ReadToEnd();
yield return fText;
responseText = fText.Result;
}
var cookies = new Cookie[response.Cookies.Count];
response.Cookies.CopyTo(cookies, 0);
yield return new Result(new Response {
Body = responseText,
ContentType = response.ContentType,
StatusCode = response.StatusCode,
StatusDescription = response.StatusDescription,
Cookies = cookies
});
}
}
示例7: Map
/// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <param name="request"></param>
/// <param name="result"></param>
/// <param name="statusCode"></param>
/// <param name="exception"></param>
/// <returns></returns>
public Attachment Map(string key, HttpWebRequest request, IAsyncResult result, out HttpStatusCode statusCode,
out Exception exception)
{
try
{
var response = request.EndGetResponse(result) as HttpWebResponse;
Stream stream = response.GetResponseStream();
statusCode = response.StatusCode;
exception = null;
var headers = new NameValueCollection();
foreach (string headerKey in response.Headers.AllKeys)
{
headers.Add(headerKey, response.Headers[key]);
}
return new Attachment
{
Data = stream.ReadData(),
Etag = new Guid(response.Headers["ETag"]),
Metadata = headers.FilterHeaders(isServerDocument: false)
};
}
catch (WebException ex)
{
var httpWebResponse = ex.Response as HttpWebResponse;
if (httpWebResponse == null)
{
throw;
}
statusCode = httpWebResponse.StatusCode;
exception = AsyncServerClient.ExtractException(httpWebResponse);
if (httpWebResponse.StatusCode == HttpStatusCode.Conflict)
{
JObject conflictsDoc = JObject.Load(new BsonReader(httpWebResponse.GetResponseStream()));
string[] conflictIds =
conflictsDoc.Value<JArray>("Conflicts").Select(x => x.Value<string>()).ToArray();
throw new ConflictException("Conflict detected on " + key +
", conflict must be resolved before the attachment will be accessible")
{
ConflictedVersionIds = conflictIds
};
}
if (httpWebResponse.StatusCode == HttpStatusCode.NotFound)
{
return null;
}
throw;
}
}
示例8: ResponseCallback
private void ResponseCallback(IAsyncResult asyncResult)
{
webRequest = (HttpWebRequest)asyncResult.AsyncState;
HttpWebResponse webResponse = (HttpWebResponse)webRequest.EndGetResponse(asyncResult);
MemoryStream tempStream = new MemoryStream();
webResponse.GetResponseStream().CopyTo(tempStream);
Dispatcher.BeginInvoke(() =>
{
BitmapImage image = new BitmapImage();
image.CreateOptions = BitmapCreateOptions.None;
image.SetSource(tempStream);
DownloadResultImage.Source = image;
DownloadStatusText.Text = "Download completed.";
});
}
示例9: ProcessResponse
private void ProcessResponse(Action<List<DilbertItem>> success, Action<Exception> error, HttpWebRequest request, IAsyncResult result)
{
try
{
var response = request.EndGetResponse(result);
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
var text = reader.ReadToEnd();
var list = ParseDilbertItemList(text);
success(list);
}
}
catch (Exception exception)
{
error(exception);
}
}
示例10: GetPricesStream
private static Stream GetPricesStream(IAsyncResult result, HttpWebRequest request)
{
Stream pricesStream = new MemoryStream();
IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
try
{
// Copy resopnse to memory
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
Stream resultStream = response.GetResponseStream();
resultStream.CopyTo(pricesStream);
pricesStream.Position = 0;
resultStream.Close();
// Copy memory to cache
IsolatedStorageFileStream pricesCacheStream = isolatedStorage.OpenFile(PricesCacheFileName, FileMode.Create, FileAccess.Write);
pricesStream.CopyTo(pricesCacheStream);
pricesStream.Position = 0;
pricesCacheStream.Close();
}
catch (WebException)
{
// If there is a problem retreiving the prices from the Internet, load the prices from the cache
pricesStream.Close();
if (isolatedStorage.FileExists(PricesCacheFileName))
{
pricesStream = isolatedStorage.OpenFile(PricesCacheFileName, FileMode.Open, FileAccess.Read);
}
else
{
pricesStream = null;
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show("Unable to retrieve prices.");
});
}
}
return pricesStream;
}
示例11: ProcessResponse
private void ProcessResponse(Action<List<Dinner>> success, Action<Exception> error, HttpWebRequest request, IAsyncResult result)
{
try
{
var response = request.EndGetResponse(result);
using (var stream = response.GetResponseStream())
{
using (StreamReader sr = new StreamReader(stream))
{
using (JsonReader reader = new JsonTextReader(sr))
{
JsonSerializer serializer = new JsonSerializer();
var list = serializer.Deserialize<List<Dinner>>(reader);
success(list);
}
}
}
}
catch (Exception exception)
{
error(exception);
}
}
示例12: GetResponse
/// <summary>
/// Gets response text from the specified request.
/// </summary>
/// <param name="request">Request object.</param>
/// <returns>Response from server.</returns>
public string GetResponse(HttpWebRequest request, IAsyncResult result)
{
return ReadResponseString(request.EndGetResponse(result));
}
示例13: GetHttpResponse
void GetHttpResponse(HttpWebRequest request, Action<HttpResponse> callback)
{
request.BeginGetResponse(ar =>
{
try
{
var response = (HttpWebResponse)request.EndGetResponse(ar);
var result = new HttpResponse();
using (response)
{
result.ContentType = response.ContentType;
result.ContentLength = response.ContentLength;
result.RawBytes = response.GetResponseStream().ReadAsBytes();
result.Content = result.RawBytes.GetString();
result.StatusCode = response.StatusCode;
result.StatusDescription = response.StatusDescription;
result.ResponseUri = response.ResponseUri;
result.ResponseStatus = ResponseStatus.Completed;
if (response.Cookies != null)
{
foreach (Cookie cookie in response.Cookies)
{
result.Cookies.Add(new HttpCookie
{
Comment = cookie.Comment,
CommentUri = cookie.CommentUri,
Discard = cookie.Discard,
Domain = cookie.Domain,
Expired = cookie.Expired,
Expires = cookie.Expires,
HttpOnly = cookie.HttpOnly,
Name = cookie.Name,
Path = cookie.Path,
Port = cookie.Port,
Secure = cookie.Secure,
TimeStamp = cookie.TimeStamp,
Value = cookie.Value,
Version = cookie.Version
});
}
}
foreach (var headerName in response.Headers.AllKeys)
{
var headerValue = response.Headers[headerName];
result.Headers.Add(new HttpHeader { Name = headerName, Value = headerValue });
}
response.Close();
}
this.ExecuteCallback(result, callback);
}
catch (Exception e)
{
OnError(e, callback);
}
}, null);
}
示例14: GetDataAsync
private async Task<Stream> GetDataAsync( HttpWebRequest request )
{
Task<WebResponse> task = Task.Factory.FromAsync(
request.BeginGetResponse,
asyncResult =>
{
try
{
return request.EndGetResponse( asyncResult );
}
catch( WebException )
{
return null;
}
},
null );
var returnTask = await task.ContinueWith( t =>
ReadStreamFromResponse( t.Result ) );
return await returnTask;
}
示例15: GetResponseCallback
private static void GetResponseCallback(IAsyncResult asynchronousResult, HttpWebRequest request,
string filename)
{
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
HttpStatusCode rcode = response.StatusCode;
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
myIsolatedStorage.DeleteFile(DIR + "\\" + filename);
}
SendAllExceptionsToServer(); //Keep sending files until all are submitted!
}