I am working on flutter application with AWS AppSync in that I am using the end URL of AWS server but when I try to execute the query I am getting below error
I am working in proxy setting but is not effecting this URL it's working perfectly in native android application
SocketException: OS Error: Connection refused, errno = 111, address = XXXXXXXXXXXXX.appsync-api.ap-south-1.amazonaws.com port -43872
I have a search on google but they mention the internet permission in not added in the manifest file but after added the permission I am facing the same issue.
Below is the code on the AWS app sync execute method where I am getting the error.
Future<Map> execute({
#required String endpoint,
#required String query,
#required Map variables,
#required String accessToken,
Database cache,
CachePriority priority = CachePriority.network,
}) async {
var body = jsonEncode({"query": query, "variables": variables});
Future<Map> loadFromCache() async {
var cacheKey = getCacheKey(endpoint, body);
var data = await readCache(cache, cacheKey);
if (data != null) {
logger.fine(
'loaded from cache (endpoint: ${endpoint.toRepr()}, requestBody: ${body.toRepr()}, cacheKey: $cacheKey)',
);
}
return data;
}
if (cache != null && priority == CachePriority.cache) {
var data = await loadFromCache();
if (data != null) return data;
}
logger.fine('POST ${endpoint.toRepr()} - ${body.toRepr()}');
http.Response response;
try {
response = await http.post(
endpoint,
headers: {
HttpHeaders.authorizationHeader: AWSaccessToken,
HttpHeaders.contentTypeHeader: ContentType.json.mimeType,
"x-api-key" :AWS_APP_SYNC_KEY,
},
body: body,
);
} catch (e) {
var shouldFallback = cache != null && priority == CachePriority.network;
if (!shouldFallback || !isNetworkError(e)) rethrow;
logger.finest('network error encountered; falling back to cache - $e');
var data = await loadFromCache();
if (data != null) {
return data;
} else {
rethrow;
}
}
if (response.statusCode != HttpStatus.ok) {
throw HttpError(response);
}
logger.fine(
'loaded from network (endpoint: ${endpoint.toRepr()}, requestBody: ${body.toRepr()})',
);
var result = jsonDecode(response.body);
var data = result["data"];
if (cache != null) {
var cacheKey = getCacheKey(endpoint, body);
await updateCache(cache, cacheKey, data);
logger.fine(
'updated cache (endpoint: ${endpoint.toRepr()}, requestBody: ${body.toRepr()}, cacheKey: $cacheKey)',
);
}
return data;
}
you are connecting to the wrong port, I mean the port you are connecting to from your client has no listener/server, or the port and public IP is not exposed to the internet on your server side
Related
So this is my first time publishing a Flutter app to the Google Play Store. I wanted to create something simple so I could learn the entire process. So I created a simple Trivia App.
When I run the app from my phone or emulator (Android or iPhone) the free API that I'm using here loads the categories without any issues.
The issue I'm having is when I publish the app to the Play Store, the API doesn't load and I don't even get an error message. Just a blank screen.
Here is the API service call in my app:
static Future<List<Category>> fetchCategories() async {
const url = "https://opentdb.com/api_category.php";
var response;
try {
response = await http.get(url);
if (response.statusCode == 200) {
var jsonString = response.body;
final Map<String, dynamic> responseData = json.decode(jsonString);
var list = responseData['trivia_categories'] as List;
var _items = list.map((i) => Category.fromJson(i)).toList();
return _items;
} else {
return null;
}
} on Exception {
throw response.statusCode;
}
}
And this is the code in the controller that calls the API's method.
void fetchCategories() async {
// flag as loading.
isLoading(true);
try {
//get categories from API server
var categories = await ApiServices.fetchCategories();
if (categories != null) {
categories.forEach((Category categoryItem) async {
// adjust data accordingly
categoryItem.totalQuestions =
await fetchCategoryCount(categoryItem.id);
if (userDataController.data.read(categoryItem.id.toString()) !=
null) {
// get a list of answered questions from the device and count them
List<dynamic> correctAnswers =
userDataController.data.read(categoryItem.id.toString());
categoryItem.correctAnswers = correctAnswers.length;
} else {
categoryItem.correctAnswers = 0;
}
categoryTiles.add(categoryItem);
});
}
} on Exception catch (e) {
throw new Exception("An error occured fetching the data");
} finally {
isLoading(false);
}
}
Has anyone else ran into this issue?
i using the ImagePicker package in the dart when i pick the image i want to upload this to the server with the form data but when i try to send this i give this error
" Unhandled Exception: FileSystemException: Cannot retrieve length of file, path = 'File: '/storage/emulated/0/Android/data/com.example.aloteb/files/Pictures/scaled_image_picker3594752094355545880.jpg'' "
and this is my code for sending to the server
var request = http.MultipartRequest('POST', Uri.parse(url));
request.fields.addAll({
'data': '$map'
});
request.files.add(await http.MultipartFile.fromPath('image',picproviderformdate.getPAth.toString()));
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
print(await response.stream.bytesToString());
}
else {
print(response.reasonPhrase);
}
and this is my ImagePickercode
picprovider pic = Provider.of<picprovider>(context,listen: false);
File image = await ImagePicker.pickImage(
source: ImageSource.gallery, imageQuality: 50);
setState(() {
_image = image;
});
print(_image);
pic.setpathe(_image);
can any one help me for solve this problem?
I had a similar problem a while ago, and i used the Dio dependency instead of the classical Http link.
The code is very similar, and i can gave you an example.
final File file = File("${documentDirectory.path}/picture.png");
final httpDio = dio.Dio();
final formData = dio.FormData.fromMap({
"data": "{}",
"files.image": await dio.MultipartFile.fromFile(
"${documentDirectory.path}/picture.png",
filename: "picture.png",
contentType: MediaType('image', 'png'))
});
try {
final dio.Response response = await httpDio.post(
"ApiEndpoint/avatars",
data: formData,
options: dio.Options(headers: {"Authorization": "Bearer yourTokenIfNeeded"}));
if (response.statusCode == 200) {
// Success
}
} on dio.DioError catch (e) {
if (e.response != null) {
// Error
print(e.response.data);
return;
}
}
Don't forgot to update the API endpoint and route as well as your auth authorization if you need one.
I want to use a string in this function that has the phone number of the device.
I get the phone number with this:
Future<void> initMobilNumberState() async {
if (!await MobileNumber.hasPhonePermission) {
await MobileNumber.requestPhonePermission;
return;
}
String mobileNumber = '';
try {
mobileNumber = await MobileNumber.mobileNumber;
_simCard = await MobileNumber.getSimCards;
} on PlatformException catch (e) {
debugPrint("Failed to get mobile number because of '${e.message}'");
}
if (!mounted) return;
setState(() {
var re = RegExp(r'\+[^]*');
_mobileNumber = mobileNumber.replaceRange(0, 3, ''.replaceAll(re, '+'));
});
}
My problem is that if I want to print _mobileNumber or use it in http.get I get null or a error with "Invalid Arguments"
Future<http.Response> _fetchSampleData() async {
String s = _mobileNumber;
print(s);
return http.get('http://test.php?TestPhone=' + _mobileNumber);
}
Future<void> getDataFromServer() async {
final response = await _fetchSampleData();
if (response.statusCode == 200) {
Map<String, dynamic> data = json.decode(response.body);
_list = data.values.toList();
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
showAlertNoInternet(context);
print('Failed to load data from server');
}
}
Where is my mistake?
The problem is that I want to call the phone number before it has even been fetched. So this always resulted in null. I fixed this by fetching the number when I start the app with all the other data I need.
Im implementing a simple app with a login screen using bloc pattern. The app runs fine when running on debug mode on the android emulator or on my android phone from android studio. When I tried the release-apk with no changes on the code, I encounter the Future is not a subtype of FutureOr error.
Here's the method on the bloc with the logic:
void submit() async{
_loginStateController.sink.add(LoginStateLoading());
User user = User();
user.email = emailController.text;
user.password = passwordController.text;
String responseBody = await ApiClient.postUser(user, "/login").catchError( (error){
developer.log("error_while_posting_user: " + error.toString());
String errorMessage = error.toString();
if(errorMessage == "missing email" || errorMessage == "missing password"){
errorMessage = "Datos faltantes";
}
else if(errorMessage == "incorrect email or password"){
errorMessage = "Correo o contraseƱa incorrecta";
}
else{
errorMessage = "Error inesperado";
}
_loginStateController.sink.add( LoginStateError(errorMessage));
return;
});
Map<String, dynamic> responseMap = json.decode(responseBody);
Utils.saveLoginInfo(responseMap);
_loginStateController.sink.add(LoginStateReady());
}
Here's the code where the http request is being made:
static Future<String> postUser(User user, String path) async {
Map<String, String> headers = Map();
headers["content-type"] = "application/json";
Map<String, dynamic> bodyMap = user.toJson();
String body = jsonEncode(bodyMap);
try {
final response = await http.post(
API_ENDPOINT + path, headers: headers, body: body).catchError( (error) {
return Future.error(error);
}).timeout(Duration(milliseconds: 10000));
if (response == null) {
return Future.error("request error");
}
if (response.statusCode != 200) {
String errorMessage = jsonDecode(response.body)["message"];
return Future.error(errorMessage);
}
return response.body;
}
catch (Exception) {
return Future.error(Exception.toString());
}
return "";
}
I've tried flutter clean several times and still getting the error.
have you checked if you have internet permission in the AndroidManifest.xml?
Can you try adding this line in the AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
I have a link in the back-end, so I fetch a post request to that link and receive a response. When I alert that response it gives a body init and body text in which I receive datas I need. Everything is good. But..
When I enable remote debugging and console.log that response, it gives body init and body blob (and both are empty). It stucks when I eneble debugging..
Thanks for attention ))
My code:
logIn = async (username, password) => {
// alert(`username : ${username}\n password : ${password}`);
let loginFormData = new FormData();
loginFormData.append('LoginForm[username]', username);
loginFormData.append('LoginForm[password]', password);
loginFormData.append('MacAddress', '111');
loginFormData.append('loginType', 'mobile');
try {
fetch('http://192.168.2.115/araqich_client/general/default/logout', {
method: 'POST',
body: loginFormData
});
let request = fetch('http://192.168.2.115/araqich_client/general/default/login', {
method: 'POST',
body: loginFormData
});
let loginResponseJson = await request;
if (loginResponseJson && loginResponseJson != null ) {
// let loginResponse = JSON.parse(loginResponseJson._bodyInit);
alert(JSON.stringify(loginResponseJson._bodyInit));
let status = loginResponse.status;
if (status) {
let SyncFormData = new FormData();
let accessToken = loginResponse.ACCESS_TOKEN;
SyncFormData.append('ACCESS_TOKEN', accessToken);
SyncFormData.append('MacAddress', '111');
SyncFormData.append('loginType', 'mobile');
let syncRequest = fetch('http://192.168.2.115/araqich_client/mobile/defaultA/syncAndroid', {
method: 'POST',
body: SyncFormData
});
let syncResponseJson = await syncRequest;
if (syncResponseJson && syncResponseJson != null) {
let syncResponse = JSON.parse(syncResponseJson._bodyInit);
let status = syncResponse.status;
if (!status) {
alert('Sorry(( something went wrong...');
} else {
alert('Life is good)))');
}
}
} else {
alert('else1')
}
} else {
alert('else')
}
} catch (error) {
alert(error);
}
}
Instead of using console.log statements, I'd advise using your debugger.