11. HTTP.CLIENT 사용하기
11. HTTP.CLIENT 사용하기
소스(democlient.py)
from http import client
urladdr = "www.example.com" conn = client.HTTPConnection(urladdr)
conn.request("GET","/") resp = conn.getresponse() data = resp.read().decode('utf-8') conn.close()
print(data) |
결과
<!doctype html> <html> <head> <title>Example Domain</title>
<meta charset="utf-8" /> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <style type="text/css"> body { background-color: #f0f0f2; margin: 0; padding: 0; font-family: "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
} div { width: 600px; margin: 5em auto; padding: 50px; background-color: #fff; border-radius: 1em; } a:link, a:visited { color: #38488f; text-decoration: none; } @media (max-width: 700px) { body { background-color: #fff; } div { width: auto; margin: 0 auto; border-radius: 0; padding: 1em; } } </style> </head>
<body> <div> <h1>Example Domain</h1> <p>This domain is established to be used for illustrative examples in documents. You may use this domain in examples without prior coordination or asking for permission.</p> <p><a href="http://www.iana.org/domains/example">More information...</a></p> </div> </body> </html> |
http.client 개체는 HTTPConnection 메서드로 연결 개체를 생성합니다.
• from http import client
• urladdr = "www.example.com"
• conn = client.HTTPConnection(urladdr)
연결 개체의 request 메서드를 통해 실제 요청이 이루어지며 response 메서드로 요청 결과를 반환 받습니다.
• conn.request("GET","/")
• resp = conn.getresponse()
response 개체의 read 메서드를 통해 결과 내용을 얻을 수 있습니다.
• data = resp.read().decode('utf-8')
그리고 연결 개체의 close 메서드를 통해 연결을 닫습니다.
• conn.close()
urllib를 이용하여 작성한 것과 http.client를 이용하여 작성한 것을 비교해 보면 urllib를 이용한 것이 간단한 것을 알 수 있습니다. 이는 저수준에서 제공하는 http.client를 사용할 개발자 편의를 위해 래핑하여 제공하는 고수준 라이브러리가 urllib이기 때문입니다.