Bad status code response from MultipartRequest - flutter

does anyone have any idea what could be wrong because I have no idea what could be causing the error?
When I'm connecting with my Rest Api where I have to put some String data and also 1 File by PostMan like in picture below:
https://files.fm/f/vrxe9zsnu
it all works how it shoud. I mean that it create new order in DB with BLOB and datas but then I'm trying doing this same on Mobile App project Idk why I'm getting respone status code 208 with message
{"timestamp":1647283779156,"message":"could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement"}
I'm sending there File which I get from ImagePicker library.
Future<String> multipart(File imageFile) async {
var request = http.MultipartRequest(
'POST', Uri.parse(ApiHeadersInfo().createNewOrderUrl));
request.headers.addAll({
"Authorization": "Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJwcEBnbWFpbC5jb20iLCJleHAiOjE2NDgyODIxNjR9.ZYOo2g1iexKZynpdoIkCMbsxzHhwLDNZEIj9qUlZj2GcwqLtUTcxaBS49_xPkewg-i22eKkGNjIQAMtjw5vwIQ",
"Content-type": "multipart/form-data"
});
request.files.add(await http.MultipartFile.fromPath('multipartFile', imageFile.path));
request.fields['customer'] = "newOrder.customer";
request.fields['loadingCompanyName'] = "newOrder.loadingCompanyName";
request.fields['loadingCity'] = "newOrder.loadingCity";
request.fields['loadingPostcode'] = "newOrder.loadingPostcode";
request.fields['dateOfLoading'] = "newOrder.dateOfLoading";
request.fields['unloadingCompanyName'] = "newOrder.unloadingCompanyName";
request.fields['unloadingPostcode'] = "newOrder.unloadingPostcode";
request.fields['dateOfUnloading'] = "newOrder.dateOfUnloading";
request.fields['nettoPrice'] = '11.0';
request.fields['bruttoPrice'] = '11.0';
request.fields['information'] = "newOrder.information";
http.Response response = await http.Response.fromStream(await request.send());
print("Result: ${response.statusCode}");
print("fields: ${request.fields}");
return response.body;
}
Any ideas what is wrong here? Maybe bad http request method I just use for it ?
Have completely no idea.
Many thanks.

Related

Dart character encoding in http request

Just learning Flutter and running into this issue when trying to call an API:
final response = await http.get(
Uri.https(apiBaseUrl, apiBaseEndpoint + "/tasks"),
headers: {
"Authorization": "Bearer " + apiKey,
},
);
print(response.body);
Part of my response contains Ä°ftar and it's supposed to be İftar. I imagine it's some encoding problem? curl gives me back the response with the proper characters.
Basically: is this a text encoding problem? If so, how do I fix my request?
Ok, after a little bit more digging on the http docs I realized it wasn't in how I made my request that needed to change, but how I handled the response. I was doing
final decodedJson = json.decode(response.body);
and I should've been doing:
final decodedJson = json.decode(utf8.decode(response.bodyBytes));
That has solved my issue!

flutter print a single value from json api

i am new to flutter and want to print only my name
my code is below i tryed but i am getting error
var resBody = await http.post(
my_url,
headers: header,
);
print(resBody.body);
i get data like this
[{name:hari,age:26,sex:male}]
i want to print name only i tryed like this but it does not work i dont know whats wrong here
print(resBody.body.name);
i getiing error
how do i print any data like that
You can access the data using key of the json object try this
var resBody = await http.post(
my_url,
headers: header,
);
final data=jsonDecode(resBody.body)//Parses the string and returns the resulting Json object
print(data[0]["name"]
Try below code,and used jsonDecode(resBody.body)['name'] jsonDecode
var resBody = await http.post(
my_url,
headers: header,
);
final jsonData=jsonDecode(resBody.body)['name'];//it prints only name of your json string
print(jsonData);

Line after await http response in Flutter app does not execute

I want to fetch a result from Flask API after sending http.MultipartFile request to server.
like this:
Future<String> upload(List<int> filename, String url) async {
//filename : binary conversion of string
//String url : api address
print("Inside Upload future!");
var request = http.MultipartRequest('POST', Uri.parse(url));
request.files.add(
http.MultipartFile.fromBytes('file', filename, filename: 'files.txt'));
print("Sending Request!");
http.Response response = await http.Response.fromStream(await request.send());
print("request sent! now returning");
var rtr = response.body;
return rtr;
}
But the problem is it does not return, and output after execution is The print after await is not executed why??:
Inside Upload future!
Sending Request!
I am sending a String to Flask API like:
It works correctly, it is receiving a string and then replying with the same string with some modifications.
#app.route('/test_api', methods=['GET', 'POST'])
def test_api():
uploaded_file = request.files['file']
file_content = uploaded_file.read().splitlines()
uploaded_file.seek(0)
file_pretty = uploaded_file.read()
a = runkey(file_pretty)
//takes string agrument and returns manipulated string
uploaded_file.seek(0)
filename = secure_filename(uploaded_file.filename)
resp = make_response(a)
resp.headers['Content-Type'] = 'text/plain;charset=UTF-8'
n = filename
resp.headers['Content-Disposition'] = 'attachment;filename='+'n'
return resp ```
I Solved this, By Adding
resp.headers['Access-Control-Allow-Origin'] = '*'
//before returning response to client
to the FlaskAPI response.
actually, I thought there's an error in Dart somewhere. But it was hiding in Chrome debugging, Since I am using Flutter Web.
The error is of Cross-Origin not allowed due to access control.

Converting my Postman Call to Dart/Flutter API Call

I hope to use nutritionix api to get food information for the users of my application, I manage to get the call to work in Postman, however I cannot convert it to dart code. I am getting this error: '{message: Unexpected token " in JSON at position 0}'
Here is my (POST) postman call:
Here is my attempt at converting that to dart code:
Future<void> fetchNutritionix() async {
String url = 'https://trackapi.nutritionix.com/v2/natural/nutrients';
Map<String, String> headers = {
"Content-Type": "application/json",
"x-app-id": "5bf----",
"x-app-key": "c3c528f3a0c68-------------",
"x-remote-user-id": "0",
};
String query = 'query: chicken noodle soup';
http.Response response =
await http.post(url, headers: headers, body: query);
int statusCode = response.statusCode;
print('This is the statuscode: $statusCode');
final responseJson = json.decode(response.body);
print(responseJson);
//print('This is the API response: $responseJson');
}
Any help would be appreciated! And, again thank you!
Your postman screenshot shows x-www-form-urlencoded as the content-type, so why are you changing that to application/json in your headers? Remove the content type header (the package will add it for you) and simply pass a map to the body parameter:
var response = await http.post(
url,
headers: headers,
body: {
'query': 'chicken soup',
'brand': 'acme',
},
);
Also you can now generate Dart code (and many other languages) for your Postman request by clicking the Code button just below the Save button.
click the three dotes button in request tab and select code option then select your language that you want convert code to
review the query you're posting
your Postman input is x-www-form-urlencoded instead of plain text
String query = 'query: chicken noodle soup';
why don't you try JSON better
String query = '{ "query" : "chicken noodle soup" }';

How to get query params in a server request in flutter?

In order to authenticate with Imgur on a mobile app, I decided to spawn an http server on port 8585 in order to complete the oauth flow. The request is read and a response is written, but I cannot access the queryparameters from the url.
I already tried using uri.queryparameters["access_token"], but null is returned.
the server is spawned as follows:
Future<Stream<String>> _server() async {
final StreamController<String> onCode = new StreamController();
HttpServer server =
await HttpServer.bind(InternetAddress.loopbackIPv4, 8585);
server.listen((HttpRequest request) async {
print(request.uri.hashCode);
final String accessToken = request.uri.queryParameters["access_token"];
request.response
..statusCode = 200
..headers.set("Content-Type", ContentType.html.mimeType)
..write("<html><h1>You can now close this window</h1></html>");
await request.response.close();
await server.close(force: true);
onCode.add(accessToken);
await onCode.close();
});
return onCode.stream;
}
the url the server gets is of the sort: http://localhost:8585/callback#access_token=your_token_here&expires_in=315360000&token_type=bearer&refresh_token=_your_refresh_token_here
Can anyone help me? I've been stuck on this for two whole days!
It returns null because query parameters start with ? at the beginning but in this link, there is a # before the query parameters and replacing it with a ? does solve the problem.
solution 1:
var uri =Uri.parse('http://localhost:8585/callback#access_token=your_token_here&expires_in=315360000&token_type=bearer&refresh_token=_your_refresh_token_here');
var newUri = Uri(query: uri.toString().substring(uri.toString().indexOf('#')+1));
print(newUri.queryParameters['access_token']) // your_token_here;
solution 2:
var uri =Uri.parse('http://localhost:8585/callback#access_token=your_token_here&expires_in=315360000&token_type=bearer&refresh_token=_your_refresh_token_here');
var newUri = Uri.parse(uri.toString().replaceFirst('#', '?'));
print(newUri.queryParameters['access_token']) // your_token_here;