Fabio
Fabio

Reputation: 45

Get value from html body from Dart

I'd like to make an HTTP POST request with Dart but I need two variables that changes every time I reload the page.

For the first variable, I solved the problem with a GET request and extracted a JSession cookie in the response header.

The second variable is inside a login form, with name="lt" and I need the value indicated with XXXXXX.

<div id="fm1Inside">
    <label for="username" accesskey="U">
        <span class="accesskey" title="U: accesskey">U</span>sername:
    </label>
    <input id="username" name="username" class="required" tabindex="10" type="text" value="" size="25" autocomplete="false"/>
    <label for="password" accesskey="P">
        <span class="accesskey" title="P: accesskey">P</span>assword:
    </label>
    <input id="password" name="password" class="required" tabindex="20" type="password" value="" size="25"/>
    <input id="submit" class="btn-submit" name="submit" accesskey="L" value="Login" tabindex="40" type="submit" />
    <input type="hidden" name="lt" value="XXXXXX" />
    <input type="hidden" name="_eventId" value="submit" />
</div>

Now, I don't know how to achieve this on dart. I searched how to do it with HTML and I found this:

document.getElementsByName("lt")[0].value;

It works, but how can I do this on dart?

I've also tried this code on Dart

Response response = await get(url);
print(response.body);

but the console in Android Studio doesn't print all the html document, just few lines.

If anyone can help me, this is the website

Upvotes: 3

Views: 4667

Answers (2)

Fabio
Fabio

Reputation: 45

I've solved using this solution. I know this isn't the best way to achieve this, but it works. If anyone has a better solution, I'd really appreciate it.

var client = new HttpClient();
var uri = Uri.parse(url);
var request = await client.getUrl(uri);
var response = await request.close();
var responseBody = await response.transform(utf8.decoder).join();
responseBody = responseBody.substring(responseBody.indexOf('name="lt"')+17);
var lt = responseBody.substring(0,responseBody.indexOf('" />'));

Upvotes: 0

Overmachine
Overmachine

Reputation: 1733

you need to import the html package and then parse the body response and then you can use some of the provided methods to query the dom.

Response response = await get(url);
var document = parse(response.body);
var inputElement = document.querySelector('[name="lt"]').value;

Upvotes: 2

Related Questions