Flutter Dio Can't Make POST Requests [closed] - android

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I'm trying to perform a POST request in a Flutter application using the Dio Plugin. I have the following code and I don't seem to know why it's not working. It sends empty data to my API.
Code:
Future<String> sendRequest(String phone, int status) async {
String status = '';
print(sendConnectionUrl);
String bearerToken = await Endpoints.getBearerToken();
try {
Response response = await Dio().post(
'https://my.web.server/api',
data: json.encode({ "mobile": phone, "status": status }),
options: Options(
headers: {
'Accept': 'application/json',
'Authorization': 'Bearer ' + bearerToken
}
)
);
// The code doesnt even get here, it goes straight to the catch
print(response.toString());
print('status: ' + response.statusCode.toString());
var jsonData = json.decode(response.toString());
if (jsonData['error'] == '0') {
status = 'ok';
}
else {
status = 'failed';
}
}
catch (e) {
print('exception: ' + e.toString());
Future.error(e.toString());
}
return status;
}
But sending the request in POSTMAN works.

This means you're server is expecting formData and you're sending data via data params. As far as i know Dio doesn't support formData . To solve this, you should either change your API to suit this requirement or use httppackage here
import 'package:http/http.dart' as http;
var url = 'https://example.com/whatsit/create';
var response = await http.post(url, body: {'name': 'doodle', 'color': 'blue'});
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
print(await http.read('https://example.com/foobar.txt'));

Try this:
Future<String> sendRequest(String phone, int status) async {
String status = '';
print(sendConnectionUrl);
String bearerToken = await Endpoints.getBearerToken();
Formdata form=FormData.fromMap({
"mobile": phone, "status": status
})
try {
Response response = await Dio().post(
'https://my.web.server/api',
data: form,
options: Options(
headers: {
'Accept': 'application/json',
'Authorization': 'Bearer ' + bearerToken
}
)
);
// The code doesnt even get here, it goes straight to the catch
print(response.toString());
print('status: ' + response.statusCode.toString());
var jsonData = json.decode(response.toString());
if (jsonData['error'] == '0') {
status = 'ok';
}
else {
status = 'failed';
}
}
catch (e) {
print('exception: ' + e.toString());
Future.error(e.toString());
}
return status;

try this
FormData form = FormData.fromMap({"url": url});
Response response = await (Dio()).post(requestUrl, data: form, cancelToken: token);

Related

Unable to upload multiple image in flutter android application

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.

Upload image to the server with the form data in flutter

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.

SyntaxError: JSON Parse error: Unrecognized token '<' for React Native

I'm trying to send a fetch request using post to an api, I'm doing a search using a keyword and it should return a JSON containing users, whenever I try this on Android using expo it doesn't work however it seems to work on iOS using expo. The error I get back is a JSON parse error, I get a status code of 308.
import User from '../../Model/User';
import { BearerToken } from '../../Constants/BearerToken';
export const GETRESULTS = 'GETRESULTS';
export const getResults = (item) => {
return async dispatch => {
const response = await fetch("https://example.com",
{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': BearerToken
},
body: JSON.stringify({
query: item
}),
redirect: 'follow'
}
);
console.log(response.status);
if(!response.ok) {
console.log("fack off");
const errorResData = await response.json();
console.log(errorResData);
let message = 'Something went wrong';
throw new Error(message);
}
const resData = await response.json();
const searchResultsArray = [];
for(const searchResult in resData){
searchResultsArray.push(new User(
resData[searchResult].education,
resData[searchResult].email,
resData[searchResult].full_name,
resData[searchResult].gender,
resData[searchResult].job_title,
resData[searchResult].location,
resData[searchResult].password,
resData[searchResult].phone,
resData[searchResult].preferred_name,
resData[searchResult].profile_image,
resData[searchResult].profile_type,
resData[searchResult].score,
resData[searchResult].short_bio,
resData[searchResult].story
)
);
}
dispatch({type: GETRESULTS,usersArray:searchResultsArray});
};
};
What worked for me was putting 'https://example.com/search/' basically at a slash at the end fixed it for me

DioError [DioErrorType.RESPONSE]: Http status error [400] Exception

I am developing a Flutter Restful web application and the web api backend as asp.net core. When i try to send the form data using post request it is throwing this error
DioError [DioErrorType.RESPONSE]: Http status error [400] Exception
Code
onPressed: () async {
String email_value = emailController.text;
String password_value = passController.text;
String fullname_value = fullnameController.text;
var repassword_value = repassController.text;
print("$email_value");
if (password_value == repassword_value) {
try{
Dio dio = Dio();
var body = jsonEncode(
{
'FullName': '$fullname_value',
'Email': '$email_value',
'Password': '$password_value'
}
);
print("Body" + body);
Response response = await dio.post("http://iamtv.chainuniverse.com/api/Accounts/Register",
data: body,
options: Options(
contentType: Headers.jsonContentType,
)
);
var jsonData = json.decode(response.data);
print(jsonData);
if (response.statusCode > 200 &&
response.statusCode < 250) {
print("Sucess");
await loginAction();
print("Registered");
}
else{
print(jsonData);
}
But when i send data manually without using textcontroller Text it works. Please help me to fix this
Working perfectly in POSTMAN
Late answer, may help you.
I was getting same error with Dio and form-data. It worked! after adding contentType
FormData formData = FormData.fromMap({
"image-param-name": await MultipartFile.fromFile(
imageFile.path,
filename: fileName,
contentType: new MediaType("image", "jpeg"), //add this
),
});
complete code
var dio = Dio();
String fileName = imageFile.path.split('/').last;
FormData formData = FormData.fromMap({
"image-param-name": await MultipartFile.fromFile(
imageFile.path,
filename: fileName,
contentType: new MediaType("image", "jpeg"), //add this
),
});
var response = await dio.post(
"url",
data: formData,
options: Options(
headers: {
"Authorization": auth-token
},
),
onSendProgress: (int sent, int total) {
debugPrint("sent${sent.toString()}" + " total${total.toString()}");
},
).whenComplete(() {
debugPrint("complete:");
}).catchError((onError) {
debugPrint("error:${onError.toString()}");
});

How to post int/integer value as json from dart/flutter

I am using asp.net core web API as back-end. There is a method that accepts a single integer value.
Method([FromBody] int value)
I want to post the integer value from dart/flutter.
I tried the following with the dart http package.
Http.post(url, body:0,headers:{"content-type":"application/json"}
Http.post(url, body:{0},headers:{"content-type":"application/json"}
Http.post(url, body:convert.jsonEncode(0),headers:{"content-type":"application/json"}
Http.post(url, body:convert.jsonEncode({0}),headers:{"content-type":"application/json"}
All my above tries failed with error
"Invalid argument: invalid request body "0""
I had the same problem when trying to send an HTTP request to an API that has an integer as one of its arguments(age). Dart wanted me to convert the int into a string and the API was not accepting the int as a string. Hence I was getting the same error and ended up in this question.
My solution was to store the input in a map, add a header {"content-type":"application/json"} and pass the map in the body arguement.
import 'dart:convert';
import 'package:http/http.dart' as http;
Future<String> register_user() async {
var req_body = new Map();
req_body['username'] = 'John Doe';
req_body['age'] = 20; /* The integer */
final response = await http.post(
'http://127.0.0.1:8081/user/register',
headers: {'Content-Type': 'application/json'},
body: jsonEncode(req_body));
if (response.statusCode == 200) {
var object = json.decode(response.body);
return object.toString();
} else if (response.statusCode == 422) {
return 'Error';
} else {
return 'Can not connect to server';
}
}
Please refer my code
import
import 'package:http/http.dart' as http;
http request
var client = new http.Client();
client.post(Uri.encodeFull("Your url"), body: {
"param1": "value1",
"param2": 11, // integer value type
}).then((response) {
client.close();
if (this.mounted && response.statusCode == 200) {
//enter your code for change state
}
}).catchError((onError) {
client.close();
print("Error: $onError");
});
I hope it will help you.
PS:
var client = new http.Client();
var response = await client.post(Uri.encodeFull("Your Url"), body : "0", header : {/*Your headers*/"});
You can try this code.
Http.post(url, body:{"id": "0"},headers:{"content-type":"application/json"}
Can you try bellow one
var queryParameters = {
'value': '0'
};
var uri =
Uri.https('www.myurl.com', '/api/sub_api_part/', queryParameters); //replace between part and your url
var response = await http.get(uri, headers: {
HttpHeaders.contentTypeHeader: 'application/json'
});

Categories

Resources