简体   繁体   中英

I cannot seem to get anything back when using httpWebResponse

I am using the following code:

var request = (HttpWebRequest)WebRequest.Create(new Uri(addy));
request.UserAgent = "Mozilla/5.0 (Windows; U; MSIE 9.0; WIndows NT 9.0; en-US))";
request.BeginGetResponse(
    r =>
    {
        var httpRequest = (HttpWebRequest)r.AsyncState;
        var httpResponse = (HttpWebResponse)httpRequest.EndGetResponse(r);

        using (var reader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var response = reader.ReadToEnd();
            results = (String)response;
        }
    }, request);

addy is: http://maps.googleapis.com/maps/api/geocode/xml?address=limavady&sensor=false

and results is just a global string to which I want to output the results of the web request.

The problem is just that I keep getting a null value output to results and I have checked the web address and it is correct and should have output.

Any ideas on this or if you can point me in the right direction i'd be grateful

  1. The page you're requesting sends you data with Content-Encoding: gzip . Add a NuGet package SharpZipLib.WindowsPhone7 to your project, and see my sample code below.
  2. Ensure you've declared ID_CAP_NETWORKING capability.
  3. Check HttpWebResponse.StatusCode property.

     static Stream responseStream( this HttpWebResponse resp ) { if( null == resp ) return null; string enc = resp.Headers[ HttpRequestHeader.ContentEncoding ]; if( !string.IsNullOrEmpty( enc ) ) { enc = enc.ToLower(); if( enc == "gzip" ) return new GZipInputStream( resp.GetResponseStream() ); } return resp.GetResponseStream(); } 

Thanks for the help, I managed to resolve the problem using the following:

WebClient webClient = new WebClient();
        webClient.OpenReadAsync(new Uri(addy));
        webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);

    }

    void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
    {
        var reader = new StreamReader(e.Result);
        results = reader.ReadToEnd();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM