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.
Related
I have a problem with a login that I am doing, in my emulator it works correctly but when I generate the apk and test it on the phone, the API does not work.
I already assigned the Internet permission in the .xml and made tests to use Internet images and everything fine, so I discarded the permissions.
I do not know if it gives me an error because I use an http and not an https, or if someone has an idea of what is happening here they tell me, I attach my code
Code:
void _login(BuildContext context) async {
if (!_loading) {
setState(() {
_loading = true;
});
}
//print(_username.value.text);
//print(_password.value.text);
var url = Uri.parse(
"http://taquillamedicina.mdgsystem.com/index.php?route=api/loginapp");
String var1 = 'vipmedico';
String var2 =
'xxxxx';
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
Map data = {
'username': var1,
'password': var2,
'usernameapp': _username.value.text,
'passwordapp': _password.value.text
};
var jsonResponse = null;
var response = await http.post(url, body: data);
//print(response);
if (response.statusCode == 200) {
jsonResponse = json.decode(response.body);
// print(jsonResponse);
if (jsonResponse != null) {
setState(() {
_loading = false;
});
sharedPreferences.setString("client_id", jsonResponse['client_id']);
if (jsonResponse['error'] == '1') {
Navigator.of(context).pushReplacementNamed("/list");
}
}
} else {
setState(() {
_loading = false;
});
print(response.body);
}
}
To get over this, you will have add android:usesCleartextTraffic="true" to your AndroidManifest.XML file. But as advised, this isn't solving th eproblem, it's sweeping it under the carpet, but will get your task done for now.
After I upgrade the Flutter 2.0 my app is down and I add under Anroid>Src>Main>AndroidManifest.xml
android:usesCleartextTraffic="true"
API and app is worked
I am trying to upload multiple image in server using android application which is builds with flutter language. Here is the code which I am trying.
static Future postDataWithFile(......List<File> images) async {
Map<String, String> headers = {
"Accept": "application/json",
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': 'Bearer $token',
};
var request = http.MultipartRequest('POST', Uri.parse(url));
request.headers.addAll(headers);
request.fields['contact'] = insertVisitedPlace.contact;
request.fields['ownerName'] = insertVisitedPlace.ownerName;
request.fields['orgName'] = insertVisitedPlace.orgName;
request.fields['orgtype'] = insertVisitedPlace.orgType.toString();
request.fields['nextFollowup'] = insertVisitedPlace.nextFollowup ?? "";
..............................
Here I am use a List to store all image.
List<MultipartFile> allImagesAfterConvert = [];
images.forEach((image) {
allImagesAfterConvert.add(
await http.MultipartFile.fromPath(
'orgImages',
image.path,
)
);
});
Send request to server to add all images. But In the server get only one image.
request.files.addAll(allImagesAfterConvert);
try {
final response = await request
.send()
.timeout(Duration(seconds: timeoutSeconds), onTimeout: () {
throw TimeoutException("Connection time out. Please try again");
});
return _isValidResponse(response) ? response : _error(response);
} on SocketException {
throw Failure("No Internet Connection");
} on TimeoutException {
throw Failure("Request time out");
} on Error catch (e) {
throw Failure(e.toString());
}
}
Replace orgImages with orgImages[]
images.forEach((image) {
allImagesAfterConvert.add(
await http.MultipartFile.fromPath(
'orgImages[]’,
image.path,
)
);
});
This should work.
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.
I have used dialogflow fulfillment to get data from an external api. It works fine with the test console. But on being deployed on to an android app, it gives a blank response. How do I fix this? Thanks.
The code in fulfillment:
'use strict';
const axios = require('axios');
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
function welcome(agent) {
agent.add(`Welcome to my agent!`);
}
function fallback(agent) {
agent.add(`I didn't understand`);
agent.add(`I'm sorry, can you try again?`);
}
function rhymingWordHandler(agent){
const word = agent.parameters.word;
agent.add(`Here are the rhyming words for ${word}`);
return axios.get(`https://api.datamuse.com/words?rel_rhy=${word}`)
.then((result) => {
result.data.map(wordObj => {
agent.add(wordObj.word);
});
});
}
let intentMap = new Map();
intentMap.set('Default Welcome Intent', welcome);
intentMap.set('Default Fallback Intent', fallback);
intentMap.set('Rhyme Scheme', rhymingWordHandler);
agent.handleRequest(intentMap);
});
The code in MainActivity.java
public void callback(AIResponse aiResponse) {
if (aiResponse != null) {
// process aiResponse here
String botReply = aiResponse.getResult().getFulfillment().getSpeech();
Log.d(TAG, "Bot Reply: " + botReply);
showTextView(botReply, BOT);
} else {
Log.d(TAG, "Bot Reply: Null");
showTextView("There was some communication issue. Please Try again!", BOT);
}
}