Htttpurlconnection functions missing in Xamarin Forms development (Java System Conversion to C#)

Asked

Viewed 40 times

1

I have a system developed in Android Studio and am passing to Xamarin Forms in C# and this happening some errors that I am not able to solve

Summarizing what my system does: It takes the html page and transcribes line by line of html so I can do some checking.

Follow lines I’m having trouble with:

if(httpURLConnection.getResponseCode() == 200) getResponse Inputstream inputStream = new Bufferedinputstream(httpURLConnection.getInputStream()); getInputStream() does not exist

Bufferedreader bufferedReader = new Bufferedreader(new Inputstreamreader(inputStream, "UTF-8")); the variable inputStream with problems

    public string GetDados(string urlString)
    {
        string dados = string.Empty;

        try
        {
            URL url = new URL(urlString);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.OpenConnection();

            if(httpURLConnection.getResponseCode() == 200)
            {
                InputStream inputStream = new BufferedInputStream(httpURLConnection.getInputStream());

                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));

                StringBuilder stringBuilder = new StringBuilder();

                string linha;

                while ((linha = bufferedReader.ReadLine()) != null)
                {
                    stringBuilder.Append(linha);
                }

                dados = stringBuilder.ToString();

                httpURLConnection.Disconnect();

            }
        }
        catch (IOException erro)
        {

            return null;
        }

        return dados;
    }
  • 1

    I’ve been through some problems converting from Java to C#. but a hint: In c#, rarely ( not to say never ) use names like "get". (due to the default get and set of language) You said you did not find getInputStream(). Try "Inputstream" in place without the parentheses, like httpURLConnection.Inputstream

1 answer

1

A much simpler way to download content from the web is this:

private async Task<string> DownloadContent(string url)
{
    using(var client = new HttpClient())
    {
        using(var r = await client.GetAsync(new Uri(url)))
        {
            return  await r.Content.ReadAsStringAsync();
        }
    }
}

You will need the package HttpClient.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.