使用httpWebResponse时,我似乎无法获得任何回报

时间:2013-03-26 02:21:32

标签: c# windows-phone-7 httpwebrequest

我使用以下代码:

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是:http://maps.googleapis.com/maps/api/geocode/xml?address=limavady&sensor=false

,结果只是一个全局字符串,我想输出Web请求的结果。

问题只是我一直得到结果的空值输出,我检查了网址,它是正确的,应该有输出。

关于这一点的任何想法,或者如果你能指出我正确的方向,我将不胜感激

2 个答案:

答案 0 :(得分:0)

  1. 您请求的页面会使用Content-Encoding: gzip向您发送数据。将NuGet包SharpZipLib.WindowsPhone7添加到您的项目中,并查看下面的示例代码。
  2. 确保您已声明ID_CAP_NETWORKING功能。
  3. 检查HttpWebResponse.StatusCode属性。

    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();
    }
    

答案 1 :(得分:0)

感谢您的帮助,我设法使用以下方法解决了问题:

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();
    }