4

I am using the below script to make request to google. However, when I execute it, I get the error stating:

client.send("GET / HTTP/1.1\r\nHost: google.com\r\n\r\n") TypeError: a bytes-like object is required, not 'str'

On browsing for similar issues in stackoverflow, client.sendto has been recommended to use along with encoding the message. However, in my case there is no message that is passed.

The below is the script I use:

import socket
target_host = "www.google.com"
target_port = 80

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((target_host,target_port))
client.send("GET / HTTP/1.1\r\nHost: google.com\r\n\r\n")
response = client.recv(4096)
print(response)

Any pointers on correcting the issue will be appreciated.

2
  • What do you mean "there is no message"? You are clearly sending an HTTP request. Commented Apr 5, 2017 at 17:30
  • 1
    In Python 3, ""GET / HTTP/1.1\r\nHost: google.com\r\n\r\n" is a unicode string and .send() wants bytes to send over the wire. Your code tries to send the unicode string straight without encoding, which the error message rightfully complains about. Commented Apr 5, 2017 at 17:36

1 Answer 1

6

You need to choose an encoding, example:

client.send("GET / HTTP/1.1\r\nHost: google.com\r\n\r\n".encode(encoding='utf-8'))

See also: Python Socket Send Buffer Vs. Str and TypeError: 'str' does not support the buffer interface

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.