I use aiohttp to make request to my url, but I don`t know why this error occurs!!!!!
async def get_location_data(url):
try:
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
data = await response.json()
return data
except Exception:
return None
while I get the response and I want to change items of my list, this error happens:
UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-4: ordinal not in range(128)
I have searched so much about it, some people said that I should use response.text(encoding="utf-8) or response.json(encoding="utf-8)
How can I fix this error?
As other people have said, use await response.json(encoding="utf-8").
Related
so i have a cmd in a cog that suppose to set the welcome channel "welcomec" and from that its supposed to take that info and use it to post the message in the guild welcome channel but doesnt seem to work ngl can anyine help me
edited: after changing it to what RiVen told me i got a new error that I don't understand at all
main code:
welcome: event
#fright.event
async def on_member_join(member):
fright.db = fright.mongo['fright']
fright.welcome = discordmongo.Mongo(connection_url=fright.db, dbname="welcome")
dbguild = await fright.welcome.find({"_id": member.guild.id})
dbchannel = await fright.welcome.find({"welcomec": member.guild.id})
wguild = fright.get_guild(dbguild)
wchannl = await fright.fetch_channel(dbchannel)
await wchannl.send('worksss')
error:
raise HTTPException(r, data) discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body In channel_id: Value "None
NoneType error means that it doesn't correctly recognize the channel. When you use get_channel you are looking for the channel in the bot's cache which might not have your channel. You could use fetch_channel instead - which is an API call.
wchannl = await fright.fetch_channel(dbchannel)
Hi I tried to catch a socketException when the server I am consulting is not available, I tried with try{}catch{}, catchError and timeout, but it doesn't work
I need that if some time passes that the server does not respond, that it already stops waiting for it
The error is :
and I tried something like this
You are probably giving the code the wrong URL. Maybe this link will help You. Link. If You could just type in the URL and If You are using Python with flask or Django, or Node.js, that would help tremendously.
Update:
In the part where You say
final resp = await http.get(url).catchError({(onError) => print(onError)});
You should change it to this:
final resp = await http.get(url).catchError((onError) {
print(onError);
return null;
});
Because You are catching the Error in the response and only printing it. You should return null; and escape that function.
I hope this helped.
i have the follow function:
Future<Null> _loadORDER(String menssage) async {
var enZona =await ApiClient.zonaNum(menssage, apiKey);
print('enZona: $enZona');
if (enZona == 'true') {
_moveToNotification(context);
};
}
the print give me the follow message: "enZona: Instance of 'Response'"
if i test the response from postman of the api query is working normally and give me: true ,
then i hope that the print result will be : "enZona: true"
but i don't know how i do to wait the response of the ApiClient before continue with the conditional (if)
thanks for your help!
thanks i add the .body but i get the same response, the apiclient code is the follow:
final response = await http.get(baseUrl + '/shop/order/$message',
headers: {HttpHeaders.authorizationHeader: apiKey});
print("enZona: $response.body");
return response;
the print value for this is: enZona: Instance of 'Response'.body
You should do print("enZona: ${response.body}"); with the curly bracket, or you can assign response.body to some variable first.
final foo = response.body; print(foo);
If you go to the pub.dev documentation for the Response class, you will see that Response is more than the content of the response. It is a wrapper class that also includes information such as the statusCode of the response, the headers, etc.
When you saw the response in Postman, you only cared about the content of the response, that is, the body of the response. What you are looking for in your code is not the enZona instance of Response, but the body of the enZona response.
Therefore, you have to swap enZona by enZona.body when trying to access the contents of your response.
I'm creating a news application, and I get my data by JSON and in each running my app get me a crash on (response HTTP) I can't understand it:
Exception has occurred. FormatException (FormatException: Unexpected character (at character 1
<HTML></HTML> ^ )
Code:
import 'package:http/http.dart' as http;
import 'dart:convert';
class Category {
int id;
String title;
Category({
this.id,
this.title
});
static Future<List<Category>> getCategories() async {
http.Response response = await http.get("url JSON"); // <- Here carash
Map<String, dynamic> map = json.decode(response.body);
List<Category> list = [];
for(var map in map['categories']){
list.add(
Category(id: map['id'], title: map['title'])
);
}
return list;
}
}
You're doing something wrong with request I think and the api does not handle that error and throws the error as html as I guess. Anyway, the way you are decoding is not the proper way.
Few points to keep in mind when you are doing http request:
Most importantly study data type (HTML / JSON) and structure of the
data. By printing to the console or great way to use curl request or postman.
Always make sure to wrap your json.decode() with a try - catch
block, When there is a error, you can properly see what's going on
with your code.
Make sure that your response status code is 200. And handle your data occordingly.
And before iterate over the decoded response, ensure that it contains
value.
If you don't know the type or if you are not
sure, without using static type to assign decoded response body use
final (Dont always use dynamic type, my suggestion for only for situations like this). This will help you with FormatException like the situation you are facing.
Last but not least, when you want to check error messages with status code. As example,
when checking expired jwt, you are getting 500 as status code.
So only checking status code is not enough in that situation
because of 500 means internal server error.
Ex:
List list = [];
try {
final decodedBody = json.decode(response.body); // when you have error messages with response, you can also check message with status code
debugPrint(decodedBody?.toString());
if (response.statusCode == 200) {
if (decodedBody != null && map['categories'] != null) { // you can also check the data type you want here ex: (map is List)
for(var map in map['categories']){
list.add(Category(id: map['id'], title: map['title']));
}
// Below is another thrilled way to do this
// list = decodedBody.map['categories']((item) => Category(id: item['id'], title: item['title'])).toList();
}
}
} catch(e, _) {
debugPrint(e.toString());
}
Wish this helpful. Follow above steps and if there any other error let me know.
The response that you are receiving is not a JSON and so your JSON can't be decoded.
Your server is returning some HTML tags and this means you might be requesting to the wrong URL, please check the URL in PostMan or Browser and see response.
My intention is to make a GET request using the DIO or any similar HTTP client in order to receive a JSON data/body and print it to the console.
I have written the following code to achieve that.
fetchQuestion(String userIdentifier) async {
String urlToCall =
"someURLhere";
try {
Response response = await Dio().get(
urlToCall,
options: Options(headers: {
HttpHeaders.authorizationHeader: "Bearer " + userIdentifier,
}),
);
print(response.data);
} catch (e) {
print(e);
}
}
The problem with this code is, when I print response.data, only null is printed. Even though I am certain that the response data contains a JSON file.
I have checked on the backend, and I am getting a 200 status code. Additionally, printing response.headers does print the headers I expected. It is only the response.body that prints null.
Issues I have tried include
Using print(utf8.decode(response.data));
Using json.decode(response.data) -> In which case I get
NoSuchMethodError: The getter 'length' was called on null. error.
I would appreciate any kind of help regarding printing the JSON file received.
Have you printed just response to see what fields are in there.
I haven't used DIO but http package works fine for me:
import 'package:http/http.dart' as http;
...
final response = await http.get(Url);