In [43]:
# Python built in support for TCP sockets
import socket
# this just opens a 'porthole' out from my computer
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# this connects me to the other computer
mysock.connect(('www.py4inf.com', 80))
In [63]:
import socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('www.py4inf.com', 80))
mysock.send(b'GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n')
while True:
data = mysock.recv(512)
if ( len(data) < 1 ) :
break
print(data);
mysock.close()
In [55]:
import socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('www.py4inf.com', 80))
# since I need to send bytes and not a string... I add a 'b' literal before the GET
mysock.send(b'GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n')
while True:
data = mysock.recv(512)
if ( len(data) < 1 ) :
break
print(data);
mysock.close()
In [29]:
import urllib.request
fhand = urllib.request.urlopen('http://www.py4inf.com/code/romeo.txt')
# the response needs to be translated to html using read()
fhand_html = fhand.read()
print(fhand_html)
In [38]:
# a nicer version of the code...
import urllib.request
with urllib.request.urlopen('http://www.py4inf.com/code/romeo.txt') as response:
fhand_html = response.read()
#fhand_html = response.readline()
#fhand_html = response.readlines()
print(fhand_html)
# read() - will store the response as a string
# readline() - will store only the first line as a string
# readlines() - will store the response as a list
In [70]:
# https://pymotw.com/3/urllib.request/
from urllib import request
URL = 'http://data.pr4e.org/intro-short.txt'
response = request.urlopen(URL)
print('RESPONSE:', response)
print('URL :', response.geturl())
headers = response.info()
print('DATE :', headers['date'])
print('HEADERS :')
print('---------')
print(headers)
data = response.read().decode('utf-8')
print('LENGTH :', len(data))
print('DATA :')
print('---------')
print(data)
In [68]:
# getting the response code, with error handling
import urllib.request
URL = 'http://data.pr4e.org/intro-short.txt'
try:
response = urllib.request.urlopen(URL)
if response.getcode() == 200:
print('Bingo')
else:
print('The response code was not 200, but: {}'.format(
response.get_code()))
except urllib.error.HTTPError as e:
print('''An error occurred: {}
The response code was {}'''.format(e, e.getcode()))
In [ ]: