Flutter http post request gives status code 401 - flutter

I am using API to verify phone number provided by user.... on postman api give perfect response and give OTP code in response but in flutter status code 401 is returned
here is my code
Future verifyPhone(String phoneNumber) async {
try {
String token = "528724967b62c6c9e546aeaee1b57e234991ad98";
var body = <String, String>{};
body['user_number'] = phoneNumber;
var url = Uri.parse(ApiKeys.phoneVerifyApiKey);
var response = await http.post(
url,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"authentication": "Bearer $token"
},
body: body,
);
if (response.statusCode == 200) {
print("Code sent");
} else {
print("Failed to send code");
print(response.statusCode);
}
} catch (err) {
print(err.toString());
}
notifyListeners();
}
instead of "code sent" i get "failed to send code" and status code 401

EDIT
You can send form request this way
Future verifyPhone(String phoneNumber) async {
try {
String token = "528724967b62c6c9e546aeaee1b57e234991ad98";
var body = <String, String>{};
body['user_number'] = phoneNumber;
var url = Uri.parse(ApiKeys.phoneVerifyApiKey);
var headers ={
"Content-Type": "application/x-www-form-urlencoded",
"authentication": "Bearer $token"
};
var request = http.MultipartRequest('POST', url)
..headers.addAll(headers)
..fields.addAll(body);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
print("Code sent");
} else {
print("Failed to send code");
print(response.statusCode);
}
} catch (err) {
print(err.toString());
}
notifyListeners();
}
EDIT
To access :
var _data = jsonDecode(response);
var list = _data["data"];
print(list[0]['otp_code']);

Related

Flutter upload image

Get Api Flutter dont working
I tried various methods, if the link is wrong, then it should at least be displayed json text in terminal
photo should be shown
Future<dynamic> getPhotoUrl(int profileID) async {
print("get Photo url $profileID");
var client = http.Client();
var url = Uri.parse("$profileBaseUrl/api/v2/profiles/$profileID/photos");
Map<String, String> headers = {
'APIVersion': '1',
"Authorization": token,
};
var response = await client.get(url, headers: headers);
if (200 == response.statusCode) {
return response.body;
} else {
}
print("avatar url: $currentPhotoUrl");
}
tried this and it doesn't work
Future<void> getPhotoUrl(int profileID) async {
print("get photo url $profileID");
var client = http.Client();
Map<String, String> headers = {
"Authorization": token
};
final http.Response response = await client.get(
Uri.parse("$profileBaseUrl/api/v2/profiles/$profileID/photos"),
headers: headers);
if (response.statusCode == 200) {
Map responseBody = jsonDecode(response.body);
var data = responseBody["data"];
if (data.length < 1) {}
else {
currentPhotoUrl.value = data[0]["content"][0]["medium"];
}
} else {
throw WebSocketException("server error: ${response.statusCode}");
}
print("photos url: $currentPhotoUrl");
}

How to implement try statement when sending http request?

I want to create a login method to post http request. I use the following code to post user data into the server and get a response:
import 'dart:convert';
import 'dart:html';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import '../Services/baseHttp.dart' as base;
class Services {
late var token = '';
Future<http.Response> login(String username, String password) async {
var url = base.BaseURL.loginUrl;
Map data = {"username": username, "password": password};
var body = json.encode(data);
var response = await http.post(Uri.parse(url),
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
},
body: body);
print(response.statusCode);
token = response.body;
print(token);
return response;
}
}
I tried to use try catch inside the method:
Future<http.Response> login(String username, String password) async {
try {
var url = base.BaseURL.loginUrl;
Map data = {"username": username, "password": password};
var body = json.encode(data);
var response = await http.post(Uri.parse(url),
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
},
body: body);
print(response.statusCode);
token = response.body;
print(token);
return response;
} catch (e) {
print(e);
}
}
I want to send statusCode instead of print(e) when any exception is thrown. How can I do that?
To check whether a response is valid, you can check the status code if it's equal to 200 like this:
if (response.statusCode == 200){
// Do something
} else {
// Throw exception
}
Taking a look the official documentation. You will see the following:
Future<Album> fetchAlbum() async {
final response = await http
.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return Album.fromJson(jsonDecode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}

flutter Unhandled Exception: DioError [DioErrorType.response]: Http status error [422]

I have an API which sends status 201 in case of a success and if there's any error with the submitted data it sends status 422 (Unprocessable Entity) with a JSON response.
{
"message": "The given data was invalid.",
"errors": {
"mobile": [
"The selected mobile is invalid."
]
}}
I am using Dio to post user credentials (mobile, password) if I enter the correct user credential I can fetch data from it but when I enter the wrong credential gives me this error:
Unhandled Exception: DioError [DioErrorType.response]: Http status error [422]
Dio code
userLogin(
String password,
String mobile,
) async {
try {
String url = "url";
Dio dio = Dio();
dio.options.headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
};
var response = await dio.post(url, queryParameters: {
"password": password,
"mobile": mobile,
});
if (response.statusCode == 200) {
return response.data;
} catch (e) {
return e.toString();
}}
How I cloud handle error response and success?
If some of Http status codes in responses are approved then you could use validateStatus function in BaseOptions to make them valid for all dio requests.
Dio dio = Dio(
BaseOptions(
headers: {...},
validateStatus: (statusCode){
if(statusCode == null){
return false;
}
if(statusCode == 422){ // your http status code
return true;
}else{
return statusCode >= 200 && statusCode < 300;
}
},
)
);
or validateStatus function in Options of concrete request
var response = await dio.post(url,
queryParameters: {
"password": password,
"mobile": mobile,
},
options: Options(
responseType: ResponseType.json,
validateStatus: (statusCode){
if(statusCode == null){
return false;
}
if(statusCode == 422){ // your http status code
return true;
}else{
return statusCode >= 200 && statusCode < 300;
}
},
),
);
The catch method has to be added to the try. In your case it was added to if(response.statuscode ==200)
userLogin(
String password,
String mobile,
) async {
try {
String url = "url";
Dio dio = Dio();
dio.options.headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
};
var response = await dio.post(url, queryParameters: json.encode({
"password": password??"",
"mobile": mobile??"",
}));
if (response.statusCode == 200) {
return response.data;
}
else{
print(response.data);
return "request failed";
}
}catch (e) {
return e.toString();
}
My Api response was this enter image description here
I have dealt with this method by allowing it BaseOptions
here is my post API code and bingo got the solution to problem
Future postApiResponse(
String url, dynamic data, bool tokentrue, String? token) async {
dynamic responceJson;
try {
// print('here 222');
if (kDebugMode) {
print('In Dio in try');
print(url);
print(data.toString());
print(tokentrue.toString());
print(token.toString());
print('In Dio in try');
}
Dio dio = Dio(BaseOptions(validateStatus: (statusCode) {
if (statusCode == 422) {
return true;
}
if (statusCode == 200) {
return true;
}
return false;
}));
if (tokentrue == true) {
// dio.options.headers['content-Type'] = 'application/json';
dio.options.headers['Accept'] = 'application/json';
dio.options.headers["authorization"] = "Bearer $token";
} else {
dio.options.headers['Accept'] = 'application/json';
}
// print('responceJson.toString()');
Response responce = await dio
.post(
url,
data: data,
)
.timeout(const Duration(seconds: 20));
debugPrint('.toString()');
responceJson = returnResponce(responce);
debugPrint(responce.toString());
} on DioError catch (e) {
returnExceptionError(e);
}
return responceJson;
}
DioError [DioErrorType.response]: Http status error [422]
The Solution :)
Dio dio = Dio(
BaseOptions(
headers: {...},
validateStatus: (statusCode){
if(statusCode == null){
return false;
}
if(statusCode == 422){ // your http status code
return true;
}else{
return statusCode >= 200 && statusCode < 300;
}
},
)
);

Flutter How to send Http (post) Request using WorkManager Plugin

Hello Guys any help will be apprecited please,
I am unable to send Http post or get request using workmanager plugin in flutter, any solutions to this would be highly appreciated, thanks
Here is my code
any help will be appreciated
thanks
Workmanager.executeTask((task, inputData) async {
switch (task) {
case fetchBackground:
print('checkStatusnow');
final sharedPref = await SharedPreferences.getInstance();
pendingStat = sharedPref.getBool('pendingStat');
print('pendingStat $pendingStat');
// await initialStat();
String url = 'https://getStat.com/chargeStat';
try {
var param = {
'authorization_code': authoStatCode,
'email': umail,
'amount': StatFare *100,
};
String body= json.encode(param);
var response = await http.Client().post(Uri.parse(url), headers: <String, String>{
'Authorization': StatKey,
'Content-Type': 'application/json',
'Accept': 'application/json'
},body: body,
);
if (response.statusCode == 200) {
print(response.body);
print("Successfull");
final data = jsonDecode(response.body);
print(data);
if (StatFounds == null) {
print("Status Not found");
}
else {
print ('checkForSta');
}
}
else {
print(response.reasonPhrase);
print("not available");
sharedPref.setBool("Stat", true);
}
} catch (e) {
}

fetching the response from API and dealing with the errors / converting Bytestreem to Map in flutter

I am trying to communicate with a PHP backend using API but I can not reach the body of the response.
I got the base code from the postman.
And here is the data of the body response:
I need to reach the message, and the errors to show them in the UI, the problem is response.stream it's type is Bytestreem and I can not convert it to Map
My code:
Future<void> _authenticateUp(String email, String password,
String passwordconfirmation, String username, String name,
{String phonenumber}) async {
var headers = {
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest'
};
var request = http.MultipartRequest('POST', Uri.parse('$siteUrl/register'));
request.fields.addAll({
'email': email,
'password': password,
'password_confirmation': passwordconfirmation,
'username': username,
'name': name,
'phone_number': phonenumber
});
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
try {
if (response.statusCode == 200) {
await response.stream.bytesToString().then((value) {
print(value);
});
} else {
// here I want to print the message and the errors
}
} catch (e) {
throw e;
}
}
Add this As for Error your statusCode is not 200
try {
if (response.statusCode == 200) {
await response.stream.bytesToString().then((value) {
print(value);
});
} else {
await response.stream.bytesToString().then((value) {
print(value);
var jsonResponse = json.decode(response.body.toString());
var nameError = jsonResponse["errors"]["name"][0];
var emailError = jsonResponse["errors"]["email"][0];
var usernameError = jsonResponse["errors"]["username"][0];
var passwordError = jsonResponse["errors"]["password"][0];
//now can print any print(emailError);
});
}