Flutter - Server Not Seeing UserAgent in Get Request - flutter

I am sending get requests in a flutter app and my server is sending a response depending on data from the phones user agent, when i send a request from a native app there is no problem -
example: "Dalvik/2.1.0 (Linux; U; Android 10; Infinix X655C Build/QP1A.190711.020)"
but when i do the same from my flutter app on an android phone the sever sees something else.
example: "Dart/2.16 (dart:io)"
this is happening even though the get request has the headers property in the request
this is the flutter code:
Future<bool> approvedData() async {
var serverUrl = "https://appsofksenia.com/app_data";
String userAgent = await FlutterUserAgent.getPropertyAsync('userAgent');
Map<String, String> headers = {
HttpHeaders.authorizationHeader: 'Basic $userAgent',
'Content-Type': 'application/json; charset=UTF-8',
'Accept': 'application/json',
"User-Agent": userAgent,
};
http.Response res = await http.get(Uri.parse(serverUrl),headers: headers);
if(res.statusCode == 200){
if(res.body.isNotEmpty) {
dynamic response = json.decode(res.body);
var serverResponse = PrivacyResponse.fromJson(response);
var serverAnswer = serverResponse.privacy;
if (serverAnswer == "data_change") {
return true;
} else {
return false;
}
}else{
return false;
}
}else{
return false;
}
}
debug of the flutter app

I solved it by using the fk_user_agent library: https://pub.dev/packages/fk_user_agent
You can make a method like this:
Future<String> getUserAgent() async {
try {
await FkUserAgent.init();
var platformVersion = FkUserAgent.userAgent!;
return platformVersion;
} on PlatformException {
return "";
}
}
Then send the return value with the key "user-agent" in the headers Map.

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");
}

Flutter http post request gives status code 401

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']);

why flutter often occur return connection closed before full header was received

I use HTTP for connection to API, and I have tried some flutter sdk like 2.5, 2.10.5, 3 but still have same issue often occur return connection closed before full header was received. and it's can occur in random api and all apps I build in flutter.
it's example of my code
Future<dynamic> getGoodSolution() async {
final url = Uri.parse('$url');
final headers = {HttpHeaders.contentTypeHeader: 'application/json', HttpHeaders.authorizationHeader: 'Bearer mytoken123'};
var map = <String, dynamic>{};
map["xxx"] = "123";
// print(headers);
try {
final response = await client.post(url, headers: headers, body: json.encode(map));
final data = xxxFromJson(response.body);
return data;
} catch (e) {
print(e);
return null;
}
}
I solved the problem by using the send() method of the HTTP (More info) package
Future<dynamic> getGoodSolution() async {
final url = Uri.parse('$url');
final headers = {HttpHeaders.contentTypeHeader: 'application/json',HttpHeaders.authorizationHeader: 'Bearer mytoken123'};
var map = <String, dynamic>{};
map["xxx"] = "123";
try {
var request = http.Request('POST', url);
request.headers.addAll(headers);
request.body = json.encode(map);
var streamedResponse = await request.send();
var response = await http.Response.fromStream(streamedResponse);
final data = xxxFromJson(response.body);
return data;
} catch (e) {
print(e);
return null;
}
}
There is an issue ongoing on the Flutter repo which describes your problem.
One of the given workarounds is to use a HttpClient and to set the allowLegacyUnsafeRenegotiation property to true
void main() async {
final context = SecurityContext.defaultContext;
context.allowLegacyUnsafeRenegotiation = true;
final httpClient = HttpClient(context: context);
final client = IOClient(httpClient);
await client.get(Uri.parse('https://your_uri.net'));
}
This solution will only work on mobile though, the http package should not be used in Web mode.

request from flutter app mobile not working but it working in web

i am already work with this code
months ago and it work correctly but now when go to run app i have this problem but it work when run it in web
var response = await http.get(Uri.parse("url"),
headers: {
HttpHeaders.authorizationHeader : "Bearer $token",
HttpHeaders.contentTypeHeader: "application/json"
}) ;
print(+response.statusCode.toString());//status code : 500 phrase reason : internal server error
Try it This Way ( set Url -> Header -> Get Responser -> Try catch -> Return )
Future<dynamic> getSchools() async {
var url = Uri.parse(base_url + '/api/user/get_schools');
final http.Response response = await http.get(
url,
headers: <String, String>{
'Content-Type': 'application/json',
},
);
if (response.statusCode == 200) {
if (kDebugMode) {
print("200 status");
}
List<School> student = (json.decode(response.body) as List).map((data) => School.fromJson(data)).toList();
return student;
} else {
return "false";
}
}

Future Call return API key invalid error UNAUTHORIZED

I'm trying to access an api endpoint using a Future and it constantly returns
{"code":"UNAUTHORIZED","message":"Invalid API Key","timestamp":"2022-03-19T16:57:02.300792Z","trackingId":"4E98D1A6:9539_0A5D03B2:01BB_62360B5E_7DAF37:3959"}
I know the reason why it failed is obvious in the error message but I don't know where where my call is going wrong.
I'm using the correct API key
Future<void> getThingsToDo() async {
var headers = {
'exp-api-key': '*******-**My-API*-*KEY-************',
'Accept-Language': 'en-US',
'Accept': 'application/json;version=2.0',
};
try {
var url = Uri.parse(
'https://api.sandbox.viator.com/partner/products/5010SYDNEY');
var response = await http.get(url, headers: headers);
if (response.statusCode == 200) {
var jsonData = json.decode(response.body);
print('Call Worked');
return jsonData;
} else {
print(response.statusCode);
print(response.body);
}
} catch (e) {
print(e);
}
throw Exception(' There is something wrong');
}
These are the sample instructions
Foe anyone using the Viatour api unless you are a merchant don't use the sandbox version.
var url = Uri.parse(
'https://api.sandbox.viator.com/partner/products/5010SYDNEY');
to
var url = Uri.parse(
'https://api.viator.com/partner/products/5010SYDNEY');