Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Http Get Request GetResponse Error

Im trying to send a get request and get the content of a webpage. i have these code.

string url = "www.google.com";

 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
 HttpWebResponse response = (HttpWebResponse)response.GetResponse();

I found these codes from many site and it is correct but "GetResponse" is giving error. Its explanation below.

Is it a problem of Visual Studio 2012 ? It cant find GetResponse method and just find GetResponseStream method when I press G.

I tried to do this with WebClient class but WebClient cannot be found also. Do these problems occur because of Visual Studio 2012? or any reason ?

Error 1 'System.Net.HttpWebResponse' does not contain a definition for 'GetResponse' and no extension method 'GetResponse' accepting a first argument of type 'System.Net.HttpWebResponse' could be found (are you missing a using directive or an assembly reference?) C:\Users\abidinberkay1\documents\visual studio 2012\Projects\App1\App1\BlankPage1.xaml.cs 45 66 App1

like image 752
abidinberkay Avatar asked Oct 05 '22 18:10

abidinberkay


1 Answers

You're calling "response.GetResponse()." It's request.GetResponse().

Update: Based on your comments, I'll propose some new code:

private async void btnRequest_Click(object sender, EventArgs e)  // Note: async added
{
    string url = "www.google.com";
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    HttpWebResponse response = (HttpWebResponse) await request.GetResponseAsync(); // (note: await added, method call changed to GetResponseAsync()

}

I've updated your code to use the C# 5.0 async and await pattern. This allows you to easily use asynchronous methods while writing code that feels synchronous. In order to do this, I've added the async keyword to the method declaration, prior to the return type (void in this case), and I've added the await keyword prior to calling WebRequest.GetResponseAsync().

To answer your question regarding how to know which library you're using: in this case, you chose a Windows Store app. You should specifically call out what kind of project you're working on - it'll help us nail these kinds of things down faster.

like image 118
Rob Avatar answered Oct 10 '22 04:10

Rob