Reputation: 69
I want to use information from a website in an app I programm in flutter. I need to log in at the website first. The html code of the website is this:
<div>Geben Sie Ihren Benutzernamen und Ihr Passwort ein, um sich an der Website anzumelden:</div>
<!-- ###LOGIN_FORM### -->
<form action="/fuer-studierende/intranet/" target="_top" method="post" onsubmit="; return true;">
<fieldset>
<legend>Anmelden</legend>
<div>
<label for="user">Benutzername:</label>
<input type="text" id="user" name="user" value="" />
</div>
<div>
<label for="pass">Passwort:</label>
<input type="password" id="pass" name="pass" value="" data-rsa-encryption="" />
</div>
I need to fill in the user name in line 8 after "value" and the password in line 12 after "value". How can I do this in flutter?
Upvotes: 1
Views: 3532
Reputation: 51770
When you fill in those fields in a browser and hit submit
the browser sends a request to the action
url, using the method
specified in the form
tag. If the method is POST
it collects the fields, encodes them using a format called x-www-form-urlencoded
and adds that as the body of the request.
(Note that the browser may take some additional steps like running JavaScript, which may alter the values. You would need to alter your values in the same way.)
The Dart package:http
provides all these functions for you. If you provide a Map<String, String>
as the body parameter of a post
, it encodes them for you and sets the content type.
void send() async {
var form = <String, String>{
'user': 'miwa',
'pass': 'M1VVA%',
};
var res = await http.post(
'https://some.website.de/fuer-studierende/intranet/',
body: form,
);
print(res.statusCode);
print(res.body);
}
Of course, you will likely receive in response a large lump of HTML and a session cookie, which you will have to parse and extract respectively.
Upvotes: 1
Reputation: 1084
You have to use flutters WebView package to send data from Flutter to HTML using JavaScript.
Follow this short tutorial to get a quick overview off the WebView package: https://medium.com/flutter/the-power-of-webviews-in-flutter-a56234b57df2
If you assign a WebViewController to the WebView (see tutorial) you can use the controller to send JavaScript messages to the HTML webpage from Flutter.
Use the following code in the «onPageFinished» function of the WebView widget:
_webController.evaluateJavascript(
'''
var email = document.getElementById("user");
var password = document.getElementById("pass");
email.value = "${_yourFlutterUserTextController.text}";
password.value = "${_yourFlutterPasswordTextController.text}"
'''
);
As you can see you can place Flutter variables like the username and password from your Flutter app and send the JavaScript snippet to the website which executes the JavaScript.
You could also fire a button click after filling out the login...
Hope this helps and good luck!
Upvotes: 2