1

I've been trying to write a simple HTTP client as a Portable Class Library with minimum dependencies, which made me think that I should use System.Net.HttpWebRequest.

I've looked at the documentation, but it shows only GetResponse/GetResponseStream methods, which I don't have in my implementation. I only have BeginGetResponse, BeginGetResponseStream, etc. I've tried using Task.Factory.FromAsync to convert this to a Task, but that only returns a Task, not a Task<HttpWebResponse>.

Is the correct approach here to use a cast, such as the following?

var response = (Task<HttpWebResponse>)Task.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse);

Or am I missing something?

edit: I don't want to introduce dependencies on additional NuGet packages, since all I need to do is a single HTTP request in one place in a tiny library.

8
  • You should use GetResponseAsync. Not sure if that's available in a PCL though. The System.Net.HttpClient NuGet package is probably a better choice than using HttpWebRequest. Commented Aug 26, 2014 at 14:54
  • 1
    I would strongly suggest using System.Net.Http.HttpClient (nuget.org/packages/Microsoft.Net.Http) Commented Aug 26, 2014 at 14:54
  • You were looking in the wrong place. The full documentation is at WebRequest class. Commented Aug 26, 2014 at 14:59
  • 1
    But that means I need to add dependencies to my library. All I'm really doing is just a single HTTP request, it feels like an overkill to add a nuget package just for that. Commented Aug 26, 2014 at 15:11
  • 1
    @JakubArnold: But this NuGet package is focused on doing exactly what you need. Would you object to adding a reference to Microsoft.Net.Http if it was part of the base class library and not a download? Like it or not Microsoft is delivering more and more class libraries using NuGet. Commented Aug 26, 2014 at 15:29

1 Answer 1

1

If you use a generic Task<>.Factory you get a little more type-safety:

var request = WebRequest.CreateHttp("https://www.google.com");
object state = null; // or whatever state you want.
var task = Task<WebResponse>.Factory.FromAsync(
    request.BeginGetResponse,
    request.EndGetResponse, 
    state);

However, as with when you're not doing async calls, if you want an HttpWebResponse rather than just a WebResponse, you'll need to do an additional cast. And be sure to close/dispose your response:

using (var response = (HttpWebResponse) (await task))
{
    // use response
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.