HTTP GET : Header (Authorization : Bearer Token) - flutter

I am making a request in postman with the same URL mentioned below in the code and in the header passing accept and Authorization with bearer token.
In postman it is working completely fine and giving desired response but in flutter in my code it is giving 403-Forbidden Request its somehow not passing the token(i am assuming).
Future<ApiResponse<String>> getCompanyList() {
String token =
" ";
Map<String, String> headers = {
HttpHeaders.contentTypeHeader: "application/json",
HttpHeaders.authorizationHeader: "Bearer $token",
};
final String API = "https://.............";
return http.get(API,headers: headers).then((data) {
if (data.statusCode == 200 ) {
final jsonData = json.decode(data.body);
return ApiResponse<String>(data: jsonData, error: false, errorMessage: "");
}
return ApiResponse<String>(error: true, errorMessage: data.statusCode.toString());
}).catchError((_) => ApiResponse<String>(error: true, errorMessage: "An Error Occureddddd!!!"));
}
}
This is my Service Class i am calling it from my Dart class anf it is calling fine.
class ApiResponse<T> {
T data;
bool error;
String errorMessage;
ApiResponse({this.data, this.error = false, this.errorMessage});
}
ApiResponse.dart

you should pass the headers as a map
something like this
var res = await http.post(url, body: body,headers: {
"Accept": "*/*",
"Content-Type" : "application/json",
"Authorization" : "Bearer $token"
},);

Related

Patch method using dio with xxx-www-form-urlencoded produces internal server error

So, i have been trying to update user data using the patch method. The data should be of
xxx-www-form-urlencoded
Also there are two additional headers required by laravel :
Accept : application/vnd.api+json,
Content-Type : application/vnd.api+json
But when i try to use the patch method in dio it produces 500 status code error.
This is the code for the patch request :
Future<CustomerResponse> editCustomer(
String id, AddCustomerModel addCustomerModel) async {
print(addCustomerModel.toMap());
var box = await Hive.openBox("tokenBox");
String token = box.get("token");
FormData formData = FormData.fromMap({
"name": addCustomerModel.name,
"consumerType": addCustomerModel.consumerType,
"corporateType": addCustomerModel.corporateType ?? "",
"amc": addCustomerModel.amc,
"amcDate": addCustomerModel.amcDate ?? "",
"address": addCustomerModel.address,
"phoneNo[]": addCustomerModel.phoneNo,
});
try {
Response response = await dio.patch(
"${Config.baseUrl}${Config.appFunctionRoute}/id",
data: formData,
options:
Options(contentType: Headers.formUrlEncodedContentType, headers: {
"Authorization": "Bearer $token",
"Accept": "application/vnd.api+json",
"Content-Type": "application/vnd.api+json"
}));
if (response.statusCode == 200) {
return CustomerResponse.fromJson(response.data);
}
} catch (e) {
print(e);
}
return CustomerResponse();
}
So , should i change something in the server side or there is something wrong from my end.

Api request returns 415 but it doesnt have media files

I try to add an address to a server with this API, but the problem is it's returning an Error 415 message in the images, but I don't send any media files, I just send a JSON map like shown in the images as well.
although it works in the postman it returns this error in the emulator.
this is the function of the API request
Future addAddress(Placemark placemark) async {
try {
String token = DataSaver.getData(tokenKey);
Uri uri = Uri.parse("$url$usersTag/$uid$addressTag");
var response = await http
.post(
uri,
headers: <String, String>{
'userId': uid,
"Authorization": "Bearer $token",
},
body: json.encode(AddressCredintials.fromPlacemark(placemark)),
)
.timeout(timeoutDuration, onTimeout: () {
log("request TimeOut");
return http.Response('Error', 408);
});
print(response.body.toString());
if (response.statusCode == 200) {
log("address added");
} else {
print(response.statusCode);
}
} catch (e) {
print(e);
} }
this is the class I am using.
class AddressCredintials {
String govID;
String cityID;
String? villageID;
String street;
String? building;
String? apartment;
AddressCredintials(
{this.apartment,
this.building,
required this.street,
required this.cityID,
required this.govID,
this.villageID});
factory AddressCredintials.fromPlacemark(Placemark placemark) {
return AddressCredintials(
street: placemark.street,
cityID: placemark.city.id,
govID: placemark.government.id,
apartment: placemark.apartment,
building: placemark.building,
villageID: placemark.village != null ? placemark.village!.id : null);
}
Map toJson() {
return {
"governorateId": govID,
"cityId": cityID,
"areaId": villageID,
"street": street,
"buildingNo": building,
"appartmentNo": apartment
};
}
}
Add to the header this value
"content-type": "application/json"
and in case your response is also a json add this
"accept": "application/json"

Can't able to call simple API

I just want to call simple API but can't able to call. If I tried to call in Postman then get proper response.
Look at my code
Future<AppServiceModel> getAllItems({String pageID = ""}) async {
final String _url = "http://www.textsite.com/api/app-view?page_id=";
final finalURL = Uri.encodeFull(_url);
try {
return http.get(finalURL, headers: {
HttpHeaders.contentTypeHeader: 'application/x-www-form-urlencoded',
HttpHeaders.acceptHeader: "application/json",
HttpHeaders.authorizationHeader: 'Bearer $accessToken'
}).then((response) {
Map<String, dynamic> _resDic =
Map<String, dynamic>.from(json.decode(response.body));
print('===>> Response : $_resDic');
return AppServiceModel.fromJson(_resDic);
});
} catch (e) {
print("Error: $e");
return null;
}
}
I also tried to pass QueryParameters by following How do you add query parameters to a Dart http request?
But each time get response
Response : {code: 7, msg: Your login session has expired. Please login again to continue., data: []}
I'm damm sure, passing right TOKEN.
Below is output of Postman

Data not sending to api using http post

I want to post json data to an api, but the api not receive the data from the app, although I tested the api from php script and it work fine. " I Think the problem in Content-Type : application/json" but I set it in the code. Any Solutions?
BackEnd Code
--header 'Content-Type: application/json' \
--data-raw '{
"username": "some data",
"password": "some data",
"mobile": "some data",
"hash": "some data"
}'
Flutter code :
static Future<String> createNewUser(String url,{String body}) async{
Map<String,String> headers = {
"Content-type" : "application/json",
};
return await http.post(url,body: body,headers: headers).then((http.Response response){
final int statusCode = response.statusCode;
print(response.body);
if( json == null){
throw new Exception("Error while create new account");
}
return response.body;
});
}
Encoded json
CreateUser createUser = new CreateUser(
username: "someData",
password:"someData",
mobile: "someData",
hash: Validation.generateHash("someData"),
);
var body = json.encode(createUser.toMap());
CreateUser.createNewUser(Config.URL_CREATE_NEW_USER,body: body).then((res){
print(res);
try not to use await and then together on one Future value.
try following:
static Future<String> createNewUser(String url,{String body}) async{
Map<String,String> headers = {
"Content-type" : "application/json",
};
http.Response response = await http.post(url,body: body,headers: headers)
final int statusCode = response.statusCode;
print(response.body);
if( json == null){
throw new Exception("Error while create new account");
}
return response.body;
}

Passing Authorization header in post call

I have to pass header data and my code looks like this and after passing this data its giving me failed to parse header issue. What could be the reason ?
Map < String, String > userData = {
"client_id": "value",
"client_secret": "value",
"grant_type": "value"
};
Map < String, String > headersMap = {
'content-type': 'application/json',
'authorization': 'Basic <token to be passed>'
};
var jsonBody = json.encode(userData);
final encoding = Encoding.getByName('utf-8');
http.post(uri, body: jsonBody, headers: headersMap).then((http.Response r) {
print(r);
if (r.statusCode == 200) {
Scaffold.of(context).showSnackBar(new SnackBar(content: new Text("User Info Updated"), ));
} else {
print(r.statusCode);
print(r.body);
}
});
I have even used dio and passed headers data like this
Map < String, String > headers = new Map < String, String > ();
headers['Authorization'] = "Basic <token>";
headers['Content-Type'] = "application/json";
Options options = Options(
headers: headers,
);
or
var httpHeaders = {
'Authorization': "Basic <token>",
'Content-Type': "application/json"
};
dio.options.headers = httpHeaders / headers;
response = await dio.post('/oauth/token',
data: jsonBody, options: options, );
Also I have tried some Post method calls without any headers(sample post request) and it works fine
I want the header parsing issue to be gone and get proper response
Try to use the the same apostrophe ( mark in caracter ) . hope it helps
map['Authorization'] = 'Bearer ${user.accessToken}';
or
var head = {
"Authorization": "Bearer ${accessToken} ",
"content-type": "application/json"}