Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

windows phone 8 - 'System.Net.HttpWebRequest' does not contain a definition for 'GetResponse'

I am creating a method for consuming a restful GET method in Visual studio 2013, with framework 4.5. This is windows_phone_8 (targeting Phone OS 8.0) application. Here is my code.

static string HttpGet(string url)
    {
        HttpWebRequest req = WebRequest.Create(url)
                             as HttpWebRequest;
        string result = null;
        using (HttpWebResponse resp = req.GetResponse()
                                      as HttpWebResponse)
        {
            StreamReader reader =
                new StreamReader(resp.GetResponseStream());
            result = reader.ReadToEnd();
        }
        return result;
    }

But I am getting a build error as follows

'System.Net.HttpWebRequest' does not contain a definition for 'GetResponse' and no extension method 'GetResponse' accepting a first argument of type 'System.Net.HttpWebRequest' could be found (are you missing a using directive or an assembly reference?)

I don't know why it happens, the same code is working fine with Windows_application in the same environment.

Update : I have tried with the web client method also

 WebClient client = new WebClient();

            client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");

            Stream data = client.OpenRead("http://192.168.10.73:8087/cisms/mobilews/login/userNameCheck?userName=supervisor");
            StreamReader reader = new StreamReader(data);
            string s = reader.ReadToEnd();
            data.Close();
            reader.Close();

Got another set of errors ...

Error 1 'System.Net.WebHeaderCollection' does not contain a definition for 'Add' and no extension method 'Add' accepting a first argument of type 'System.Net.WebHeaderCollection' could be found (are you missing a using directive or an assembly reference?)

Error 2 'System.Net.WebClient' does not contain a definition for 'OpenRead' and no extension method 'OpenRead' accepting a first argument of type 'System.Net.WebClient' could be found (are you missing a using directive or an assembly reference?)

Error 3 'System.Net.HttpWebRequest' does not contain a definition for 'GetResponse' and no extension method 'GetResponse' accepting a first argument of type 'System.Net.HttpWebRequest' could be found (are you missing a using directive or an assembly reference?)

Update 2 :

I have changed the code as follows, based on @Gavin' answer..

static async void HttpGet(string url)
    {
        Uri uri = new Uri(url);
        string result = null;
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
        request.Method = "GET";
        using (var response = (HttpWebResponse)(await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null)))
        {
            StreamReader reader = new StreamReader(response.GetResponseStream());
            result = reader.ReadToEnd();
        }
    }

But the control goes back to the calling event, from the following line

using (var response = (HttpWebResponse)(await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null)))

any help on this would be greatly appreciated.

Answer :

I changed the code as follows and it is working now..

public async Task<string> httpRequest(string url)
        {
            Uri uri = new Uri(url);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            string received;

            using (var response = (HttpWebResponse)(await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null)))
            {
                using (var responseStream = response.GetResponseStream())
                {
                    using (var sr = new StreamReader(responseStream))
                    {

                        received = await sr.ReadToEndAsync();
                    }
                }
            }

            return received;
        }

the calling part is as follows...

private async void Button_Click(object sender, RoutedEventArgs e)
        {
            string uriString = "http://192.168.10.73:8087/cisms/mobilews/login/userNameCheck?userName=supervisor";
            var response = await httpRequest(uriString);
        }

Update 3:

I have one more issue in processing POST request. The code I have tried is given below.

static string HttpPost(string url, string[] paramName, string[] paramVal)
        {
            HttpWebRequest req = WebRequest.Create(new Uri(url))
                                 as HttpWebRequest;
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";

            // Build a string with all the params, properly encoded.
            // We assume that the arrays paramName and paramVal are
            // of equal length:
            StringBuilder paramz = new StringBuilder();
            for (int i = 0; i < paramName.Length; i++)
            {
                paramz.Append(paramName[i]);
                paramz.Append("=");
                paramz.Append(HttpUtility.UrlEncode(paramVal[i]));
                paramz.Append("&");
            }

            // Encode the parameters as form data:
            byte[] formData =
                UTF8Encoding.UTF8.GetBytes(paramz.ToString());
            req.ContentLength = formData.Length;

            // Send the request:
            using (Stream post = req.GetRequestStream())
            {
                post.Write(formData, 0, formData.Length);
            }

            // Pick up the response:
            string result = null;
            using (HttpWebResponse resp = req.GetResponse()
                                          as HttpWebResponse)
            {
                StreamReader reader =
                    new StreamReader(resp.GetResponseStream());
                result = reader.ReadToEnd();
            }

            return result;
        }

This method is having two build errors in Windows phone 8 application

Error 1 'System.Net.HttpWebRequest' does not contain a definition for 'GetRequestStream' and no extension method 'GetRequestStream' accepting a first argument of type 'System.Net.HttpWebRequest' could be found (are you missing a using directive or an assembly reference?)

Error 2 'System.Net.HttpWebRequest' does not contain a definition for 'GetResponse' and no extension method 'GetResponse' accepting a first argument of type 'System.Net.HttpWebRequest' could be found (are you missing a using directive or an assembly reference?)

Thanks Sebastian

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

WP8 supports a subset of .NET Framework 4.5.

You can adapt the code variations below for your needs:

WebRequest request = WebRequest.Create(url);
return Task.Factory.FromAsync(request.BeginGetResponse, result =>
{
    HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
    ...
}

or

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "GET";
using (var response = (HttpWebResponse)(await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null)))
{
    ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...