1

Tenho uma classe em C# para Windows que funciona normalmente, porém gostaria que ela funcionasse no Windows Phone.

A ideia é usar os métodos HTTP get e post de uma página da internet que tenha CAPTCHA.

Vou mostrar o captcha ao usuário e vou passar como post a resposta.

<input type=hidden id=viewstate name=viewstate value='";
        String StrImagemCaptcha = "<img border='0' id='imgcaptcha' alt='Imagem com os caracteres anti rob";
        String UrlImagemCaptcha = "";
        HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(UrlBase + UrlGet);
        httpWebRequest.CookieContainer = cookieContainer;
        httpWebRequest.ContentType = "application/x-www-form-urlencoded";
        httpWebRequest.Method = "GET";
        httpWebRequest.AllowAutoRedirect = false;
        //httpWebRequest.Timeout = 20000;
        try
        {
            StreamReader stHtml = new StreamReader(httpWebRequest.GetResponseStream(), Encoding.GetEncoding("ISO-8859-1"));
            HtmlResponse = stHtml.ReadToEnd();
            stHtml.Close();
            viewState = HtmlResponse;
            PosString = viewState.IndexOf(StrViewState);
            if (PosString >= 0)
                viewState = viewState.Substring(PosString + StrViewState.Length);
            PosString = viewState.IndexOf("'>");
            if (PosString >= 0)
                viewState = viewState.Substring(0, PosString);
            UrlImagemCaptcha = HtmlResponse;
            PosString = UrlImagemCaptcha.IndexOf(StrImagemCaptcha);
            if (PosString >= 0)
                UrlImagemCaptcha = UrlImagemCaptcha.Substring(PosString + 8 + StrImagemCaptcha.Length);
            PosString = UrlImagemCaptcha.IndexOf("'>");
            if (PosString >= 0)
                UrlImagemCaptcha = UrlImagemCaptcha.Substring(0, PosString);
            UrlImagemCaptcha = UrlImagemCaptcha.Replace("amp;", "");
        }
        catch (Exception ex)
        {
            _erro = ex.Message;
        }
        try
        {
            if (UrlImagemCaptcha.Length > 0)
                return UrlDominio + UrlImagemCaptcha;
            //return new System.Drawing.Bitmap(new System.IO.MemoryStream(new System.Net.WebClient().DownloadData(UrlDominio + UrlImagemCaptcha)));
            else
                return null;
        }
        catch (Exception ex)
        {
            _erro = ex.Message;
            return null;
        }
    }

Porém o Visual Studio está acusando que httpWebRequest.GetResponseStream() não existe.

Qual outra forma de fazer isso ou corrigir o atual?

1 Resposta 1

2

Os métodos de acesso a rede na plataforma do Windows Phone são todos assíncronos - você terá que usar a versão assíncrona do GetResponse, como no exemplo abaixo:

    public void Foo()
    {
        var UrlBase = "";
        var UrlGet = "";
        HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(UrlBase + UrlGet);
        httpWebRequest.Method = "GET";
        httpWebRequest.BeginGetResponse(GetResponseCallback, httpWebRequest);
    }

    void GetResponseCallback(IAsyncResult asyncResult)
    {
        HttpWebRequest httpWebRequest = (HttpWebRequest)asyncResult.AsyncState;
        HttpWebResponse response = (HttpWebResponse)httpWebRequest.EndGetResponse(asyncResult);
        StreamReader stHtml = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("ISO-8859-1"));
        var HtmlResponse = stHtml.ReadToEnd();
        // ...
    }

Uma outra alternativa é o uso da biblioteca HttpClient, que suporta o padrão de Tasks, onde você pode usar o await para não ter que "quebrar" o código em métodos diferentes:

    public async Task Foo()
    {
        var UrlBase = "";
        var UrlGet = "";
        var client = new HttpClient();
        var response = await client.GetAsync(UrlBase + UrlGet);
        var responseStream = await response.Content.ReadAsStreamAsync();
        var stHtml = new StreamReader(responseStream, Encoding.GetEncoding("ISO-8859-1"));
        var HtmlResponse = await stHtml.ReadToEndAsync();
        // ...
    }
1
  • Irei testar assim que chegar em casa e posto o resultado. Grato
    – user11968
    1/07/2014 às 14:10

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .