Creating flutter Json Login form with user Basic authentication - json

Have been stuck for quite a while on this step. can someone show me how to send a request such that upon pressing the "login" button a new instance of a user with Basic authentication is created. i would love to understand how to know how the headers are arranged to access the url database
void Login() {
final form = formKey.currentState;
if (form.validate()) {
form.save();
makePost();
}
}
second part my json methond
Future<Post> makePost() async {
String Username = "denisPos";
String Password = "moV4b90WqpHfghghsg";
final response = await http.post('http://.60.4546.109:4520/postRequest',
headers: {HttpHeaders.authorizationHeader: '$Password:$Username:$url'});
final responseJson = json.decode(response.body);
return Post.fromJson(responseJson);
}
class Post {
final String phone;
final String password;
final String body;
Post({this.phone, this.password, this.body});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
phone: json['phone'],
password: json['password'],
body: json['body'],
);
}
}

If you are talking about Basic authentication you can have something like the following code:
Future<Post> makePost() async {
String username = "denisPos";
String password = "moV4b90WqpHfghghsg";
var bytes = utf8.encode("$username:$password");
var credentials = base64.encode(bytes);
var headers = {
"Accept": "application/json",
"Authorization": "Basic $credentials"
};
var url = ...
var requestBody = ....
http.Response response = await http.post(url, body: requestBody, headers: headers);
var responseJson = json.decode(response.body);
return Post.fromJson(responseJson);
}
If you are sending a GET request you can omit the requestBody altogether.
http.Response response = await http.get(url, headers: headers);

Future<http.Response> post() async {
var url = 'http://xxxxxxxxxxxxx;
String password = "xxxxxxxxxxxxxxxx;
String username = "
var bytes = utf8.encode("$username:$password");
var credentials = base64.encode(bytes);
var headers = {
"Content-Type": "application/json",
"Authorization": "Basic $credentials"
};
var requestBody = jsonEncode({ 'phone': phone, 'pass': pass});
http.Response response = await http.post(
url, body: requestBody, headers: headers);
var responseJson = json.decode(response.body);
print(Utf8Codec().decode(response.bodyBytes));
print("Body: " + responseJson);
}

Related

Server API not accept JSON edcoded data Flutter

Edit:
After hours of work, i might because when i send "content-type": "application/json", it send "application/json; charset=utf-8" to server. How to remove ; charset=utf-8 from header?
Edit2:
The problem is because flutter send charset=utf-8 in Content-type. I fix by contact my backend developer to allow "application/json; charset=utf-8" in Content-type header
I send post request to server, return error
{"error":"true","code":"30","message":" Data must JSON"}
This is my code:
Future<void> _getToken() async {
final url =
Uri.parse("http://apimobile.xxxx.co.id/Apimobile/auth");
final Map<String, String> data = {
"username": "xxxx",
"password": "xxxx"
};
try {
final response = await http.post(url,
headers: {
"Content-Type": "application/json",
"accept": "application/json",
},
body: jsonEncode(data));
print(response.body);
final responseData = jsonDecode(response.body);
_token = responseData["message"];
} catch (error) {
throw error;
}
}
Is there something wrong in my code? 🤔
The API work on Postman, ThunderClient VS Code, and React Native
Thanks for your help
Create model like this:
import 'dart:convert';
LoginData loginDataFromJson(String str) => LoginData.fromJson(json.decode(str));
String loginDataToJson(LoginData data) => json.encode(data.toJson());
class LoginData {
LoginData({
required this.username,
required this.password,
});
final String username;
final String password;
factory LoginData.fromJson(Map<String, dynamic> json) => LoginData(
username: json["username"],
password: json["password"],
);
Map<String, dynamic> toJson() => {
"username": username,
"password": password,
};
#override
String toString() {
return '$runtimeType($username, $password)';
}
#override
bool operator ==(Object other) {
if (other is LoginData) {
return username == other.username && password == other.username;
}
return false;
}
#override
int get hashCode => hash2(username, password);
}
And now you can write your code like this:
Future<void> _getToken() async {
final url =
Uri.parse("http://apimobile.xxxx.co.id/Apimobile/auth");
final LoginData data = LoginData(
username: "xxxx",
password: "xxxx"
);
try {
final response = await http.post(url,
headers: {
"Content-Type": "application/json",
"accept": "application/json",
},
body: data.toJson());
print(response.body);
final responseData = jsonDecode(response.body);
_token = responseData["message"];
} catch (error) {
throw error;
}
}
The headers field in the http.post method has to be changed to have Content-Type equal to application/json and accept equal to application/json.
Future<void> _getToken() async {
final url =
Uri.parse("http://apimobile.xxxx.co.id/Apimobile/auth");
final Map<String, String> data = {
"username": "xxxx",
"password": "xxxx"
};
try {
final response = await http.post(url,
headers: {
"Content-Type": "application/json",
"accept": "application/json",
},
body: jsonEncode(data));
print(response.body);
final responseData = jsonDecode(response.body);
_token = responseData["message"];
} catch (error) {
throw error;
}
}
Try encode your data using convert
import 'dart:convert' as convert;
//...
const JsonEncoder encoder = JsonEncoder();
final response = await http.post(url,
headers: {
"Content-Type": "application/json",
"accept": "application/json",
},
body: encoder.convert(data)
);
Hope this will help

Flutter Registration with API

I successfully can login with my API connection also can display the data in my app.
I follow the same method for the registration to send data in API So that I can login.
But the registration is not happening, although it didn't show any error. My SnackBar showing You are already registered . But When I try to login with the data which I provided in registration form, its showing user not found( Obvious reason registration process didn't perform). Is there any problem with my API MODEL?
Here is my Parameters
{
"Email":"qwer#gmail.com",
"Mobile":"1237891",
"Password":"9991",
"RetypePassword":"9991"
}
And here is the Json response
{
"Status": "1",
"Message": "You are registered successfully",
"UserData": {
"Name": "qwer#gmail.com",
"EncUserId": "IS0QOCrLby8Ft1kbkzn/mg=="
}
}
After that I created a registration form, when user click the Register button it's run my API function registrationOfuser()
Future <void> registrationOfuser(String email, contact, pass,conpass) async{
var jsonResponse ;
Map data = {
'Email': email,
'Mobile': contact,
'Password': pass,
'RetypePassword': conpass,
};
print(data);
String body = json.encode(data);
var url = 'http://myurl/home/djkjkfjkjfwkjfkwjkjfkjwjfkwjfkwf';
var response = await http.post(
url,
body: body,
headers: {
"Content-Type": "application/json",
"accept": "application/json",
"Access-Control-Allow-Origin": "*"
},
);
print(response.body);
print(response.statusCode);
if (response.statusCode == 200) {
jsonResponse = json.decode(response.body.toString());
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content:Text(" ${jsonResponse['Message']}"))) ;
//Or put here your next screen using Navigator.push() method
print('success');
} else {
print('error');
}
}
And here is my MODEL
class RegistrationApiResponse {
RegistrationApiResponse({
required this.status,
required this.message,
required this.userData,
});
String status;
String message;
//UserData userData;
UserData? userData;
factory RegistrationApiResponse.fromJson(Map<String, dynamic> json) => RegistrationApiResponse(
status: json["Status"],
message: json["Message"],
userData: json["UserData"] == null? null:UserData.fromJson(json["UserData"] as Map<String, dynamic>),
}
class UserData {
UserData({
required this.name,
required this.encUserId,
});
String name;
String encUserId;
factory UserData.fromJson(Map<String, dynamic> json) => UserData(
name: json["Name"],
encUserId: json["EncUserId"],
);
}
Try to below code help:
Create TextEditingController
final TextEditingController email = new TextEditingController();
final TextEditingController contact = new TextEditingController();
final TextEditingController password = new TextEditingController();
final TextEditingController conpassword = new TextEditingController();
Create one function for registration
register(String email, contact, pass,conpass) async {
Map data = {
'Email': email,
'Mobile': contact,
'Password': pass,
'RetypePassword': conpass,
};
print(data);
String body = json.encode(data);
var url = 'Your url here';
var response = await http.post(
url,
body: body,
headers: {
"Content-Type": "application/json",
"accept": "application/json",
"Access-Control-Allow-Origin": "*"
},
);
print(response.body);
print(response.statusCode);
if (response.statusCode == 200) {
//Or put here your next screen using Navigator.push() method
print('success');
} else {
print('error');
}
}
Create Button
ElevatedButton(
child:Text('Register'),
onPressed:(){
register(email.text, contact.text, password.text, conpassword.text);
},
),
You need to get text from controller. Do as follows:
body:({
'Email':emailController.text,
'Mobile':phoneController.text,
'Password':passwordController.text,
'RetypePassword':rePasswordController.text,
}));
class ApiService {
callloginapi(
var email,
) async {
LoginReg? userModel;
Response response = await post(
Uri.parse('http://13.127.138.139/api/Login_Register_User'),
body: {
'mobile': email,
});
var jsonResponse = jsonDecode(response.body.toString());
userModel = LoginReg.fromJson(jsonResponse);
print(jsonResponse['token']);
var flag = jsonResponse['data']['flag'];
log('==========flag ===========$flag');
//return userModel;
var message = jsonResponse['message'];
if (response.statusCode == 200) {
if (flag == 'true') {
Get.offAllNamed(PageRoutes.home);
// t
emailController.clear();
print('$message');
// moveToHome(context);
} else {
// server error
print('Not Register');
}
}
}}

Flutter sending post request returning http error 500

i have been working on flutter project which accepts name and phone number of users but when i save it it shows response 500 but from post man its working fine.
but from flutter here is the code
void RegisterUsers(String names, String phone) async{
String urlInser = "https://hmmmiii.com/api/addUser";
Map<String, String> headers = {
'Content-Type': 'application/json',
//'Accept': 'application/json',
};
final msg = jsonEncode({"Name":"$names","PhoneNumber":"$phone"});
var response = await http.post(urlInser,
headers: headers,
body: msg);
print(response.statusCode);
if (response.statusCode == 200) {
print('User Registered');
} else {
print('Unsuccessful');
}
where names and phone are textController values thanks.
in postman, you are sending the request as form-data, but in your code, you are sending it as a simple JSON.
you have to use MultipartRequest instead.
final url = 'your url';
final request = http.MultipartRequest('POST', Uri.parse(url))
..fields['Name'] = 'some name'
..fields['PhoneNumber'] = 'some phonenumber';
final response = await request.send();
final responseBody = await response.stream.bytesToString();
print('RESPONSE BODY: $responseBody');

Flutter Change Password with sharedpreferences

Good day i just want to ask how do i get the sharepreferences id so i be able to change my password
class _ChangePasswordState extends State<ChangePassword> {
String c1, password, c3;
final _key = new GlobalKey<FormState>();
//i want to know how to get the id cause i got undefined id
save() async {
Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
SharedPreferences preferences = await _prefs;
String id = preferences.getString("id");
debugPrint(id);
final response =
await http.post('http://192.168.1.9/vessellog/changepass.php',
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, dynamic>{
'id': id,
'password': password,
}));
debugPrint(response.body);
final data = jsonDecode(response.body);
int value = data['value'];
if (value == 1) {
} else {
}
You need to set the value of id first.
SharedPreferences pref = await SharedPreferences.getInstance();
pref.setString('id','value you want');

Parse json in background using Dart's 'compute'

I am trying to use Json using the 'compute' method as I investigate ways to speed up my application. https://api.flutter.dev/flutter/foundation/compute.html.
No mention of an install for a package and use cases that I see do not mention any particular imports. https://dev.to/fallenstedt/compute-with-flutter-3p6o, https://github.com/flutter/flutter/issues/16265, Flutter- compute method
Error message:
Compiler message:
lib/account_control.dart:34:26: Error: Method not found: 'compute'.
parsedJson = await compute(jsonDecode, response.body);
Where I call compute
if (response.statusCode == 200) {
parsedJson = await compute(jsonDecode, response.body);
Globals.data = parsedJson;
print("Succesfully set Globals.data");
return true;
}
Class implementation
class AccountControl {
static dynamic getAccDetails() async {
var token = Globals.token;
Globals.tokenDecode = Globals.parseJwt(Globals.token);
Globals.accountId = Globals.tokenDecode["accountId"].toString();
Globals.appUserId = Globals.tokenDecode["appUserId"].toString();
Globals.partitionId = 0;
var baseUrl = Globals.baseUrl; //platform server
var accountId = Globals.accountId;
var host = Globals.host;
var accDetailsUri =
Uri.encodeFull(baseUrl + "t/rest/cp/v1.0/account/" + accountId);
print(accDetailsUri);
Map<String, String> headers = {
'Accept': 'application/json',
'Authorization': 'Bearer ' + token,
'Cache-Control': 'no-cache',
'Host': host
};
var response = await http.get(accDetailsUri, headers: headers);
var parsedJson;
if (response.statusCode == 200) {
parsedJson = await compute(jsonDecode, response.body);
Globals.data = parsedJson;
print("Succesfully set Globals.data");
return true;
}
}
}
Any feedback is appreciated
You need to import foundation.
import 'package:flutter/foundation.dart';