This question already has an answer here:
The Sorting Hat is able to look into a person's mind to learn about their talents, and can hear the thoughts of the person as well.
Hmm," said a small voice in his ear. "Difficult. Very difficult. Plenty of courage, I see. Not a bad mind either. There's talent, A my goodness, yes -- and a nice thirst to prove yourself, now that's interesting.... So where shall I put you?"
Harry gripped the edges of the stool and thought, Not Slytherin, not Slytherin.
"Not Slytherin, eh?" said the small voice. "Are you sure? You could be great, you know, it's all here in your head, and Slytherin will help you on the way to greatness, no doubt about that -- no? Well, if you're sure -- better be GRYFFINDOR!"
—Chapter 7: "The Sorting Hat", Harry Potter and the Sorcerer's Stone
Does the Sorting Hat get its mind-reading powers from the use of legilimency (the art of mind-reading)? Could someone skilled in occlumency (the art of closing one's mind against legilimency) be able to prevent the Sorting Hat from working?