http.get causes Japanese text to get jumbled - flutter

I am using following code to get data from a server that has Japanese text.
final response = await http.get(url, headers: {
'Content-Type': 'application/json',
});
I get the data correctly but all the Japanese text does not look correct. They look like
æ±äº¬éƒ½ä¸­å¤®åŒºæ—¥æœ¬æ©‹å®¤ç”º3-3-9
When I use "Postman" to check the data, it is displaying Japanese text correctly.
How do I get around this issue?
I have the same problem when I put the values.
I use;
Map<String, String> headers = {
'Content-Type': 'application/json',
'authorization': basicAuth,
};
final msg = jsonEncode(data);
final response = await http.put(
url,
headers: headers,
body: msg,
);
The data does not seems to encode correctly, when they are in Japanese.
Can someone provide some help on this ?

Related

Dart TypeError : type 'JSString' is not a subtype of type 'int' for a Http POST request

I'm building an application using flutter where the user provides a string and a set of values must be returned.
I'm unable to figure out what is the cause for the issue.I tried all the solutions provided to the questions similar to this issue but weren't successful.Any help would be really appreciated.
I converted the actual code to dart only, for easy testing online using dartpad.
import 'dart:convert' as convert;
import 'package:http/http.dart' as http;
final body = <String, String>{
"id": '1',
"language": "en",
"text": "I love this service",
};
final headers = <String, String>{
"content-type": "application/json",
"X-RapidAPI-Key": "7f980b3d2cmsh1d666b571febd6ep11df80jsna27f76c06e6b",
"X-RapidAPI-Host": "big-five-personality-insights.p.rapidapi.com",
};
void main(List<String> arguments) async {
final response = await http.post(
Uri.parse('https://big-five-personality-insights.p.rapidapi.com/api/big5'),
headers: headers,
body: [
convert.jsonEncode(body),
],
);
if (response.statusCode == 201) {
// If the server did return a 201 CREATED response,
// then parse the JSON.
print('success');
print(convert.jsonDecode(response.body));
} else {
// If the server did not return a 201 CREATED response,
// then throw an exception.
print('fail');
throw Exception('Failed to get a response.');
}
}
You have a bad value for the body argument of http.post.
The documentation for the method states:
body sets the body of the request. It can be a String, a List or a Map<String, String>. [...] If body is a List, it's used as a list of bytes for the body of the request.
Since the API you are talking to requires an array to be sent, you want to wrap the body in a list before converting it all to json (note how the brackets have shifted inside the convert method:
final response = await http.post(
Uri.parse('https://big-five-personality-insights.p.rapidapi.com/api/big5'),
headers: headers,
body: convert.jsonEncode([body]),
);
Sidenote: The API responds with statusCode 200 on a successful request, not 201; at least in my testing.
The body parameter of a post method sets the body of the request. It can be a String, a List or a Map<String, String>. If it's a String, it's encoded using encoding and used as the body of the request. The content-type of the request will default to "text/plain".
As you passed it as a List, then it expects it to be a List of integers, but you are passing it a List type (or in this specific case List type). Here is a fixed code.
final response = await http.post(
Uri.parse('https://big-five-personality-insights.p.rapidapi.com/api/big5'),
headers: headers,
body: convert.jsonEncode(body),
);

Is there any way to convert the response body to XML in flutter?

I have a get request in flutter, the response body comes as json, is there any way to have it in XML?
In the Swagger UI it comes as XML but I don't know why it comes as Json in my request.
I am using this lines:
final response = await http.get(Uri.parse(selectedURL));
print(response.body);
You probably need to set the Accept header to something like:
Accept: application/xml
Something like this might do the trick:
final response = await http.get(
Uri.parse(selectedURL),
headers: {
'Accept': 'application/xml',
},
);
print(response.body);

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

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