>  기사  >  백엔드 개발  >  Python의 http 요청 메소드 라이브러리 요약

Python의 http 요청 메소드 라이브러리 요약

高洛峰
高洛峰원래의
2016-10-17 13:07:221340검색

최근 인터페이스 테스트를 위해 Python을 사용하다가 Python에 많은 http 요청 메소드가 있다는 것을 알게 되었습니다. 오늘은 시간을 내어 관련 내용을 정리하여 공유해 드립니다.

1. Python 자동 구성 라이브러리 ---- urllib2

Python 자체 라이브러리인 urllib2가 더 일반적으로 사용됩니다. 간단한 사용법은 다음과 같습니다.

import urllib2

response = urllib2.urlopen('http: //localhost:8080/jenkins/api/json?pretty=true')

print response.read()

간단한 가져오기 요청

urllib2 가져오기

urllib 가져오기

post_data = urllib.urlencode({})

response = urllib2.urlopen('http://localhost: 8080/, post_data)

print response.read()

print response.getheaders()

이것은 게시물을 보내는 urllib2의 가장 간단한 예입니다. 코드가 많아요

2. 파이썬 자체 라이브러리 - httplib

httplib는 상대적으로 낮은 수준의 http 요청 모듈이며 urlib는 httplib를 기반으로 캡슐화되어 있습니다. 간단한 사용법은 다음과 같습니다.

import httplib
conn = httplib.HTTPConnection("www.python.org")
conn.request("GET", "/index.html")
r1 = conn.getresponse()
print r1.status, r1.reason
data1 = r1.read()
conn.request("GET", "/parrot.spam")
r2 = conn.getresponse()
data2 = r2.read()
conn.close()

Simple get request

post 요청

import httplib, urllib
params = urllib.urlencode({'@number': 12524, '@type': 'issue', '@action': 'show'})
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
conn = httplib.HTTPConnection("bugs.python.org")
conn.request("POST", "", params, headers)
response = conn.getresponse()
data = response.read()
print data
conn.close()

을 살펴보고 너무 복잡한지 살펴보겠습니다. 글을 쓸 때마다 문서를 읽어야 합니다. 세 번째 항목을 살펴보겠습니다.

3. 타사 라이브러리--요청

get 요청을 보내는 것은 매우 간단합니다.

print requests.get('http://localhost:8080).text

한 문장으로 게시물 요청을 살펴보겠습니다

payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post("http://httpbin.org/post", data=payload)
print r.text

역시 매우 간단합니다.

인증하고 싶다면 다시 살펴보겠습니다.

url = 'http://localhost:8080'
r = requests.post(url, data={}, auth=HTTPBasicAuth('admin', 'admin'))
print r.status_code
print r.headers
print r.reason

urllib2보다 훨씬 간단하고 요청에는 json 구문 분석이 제공됩니다. 훌륭해요

파이썬에서 http 요청

import urllib
params = urllib.urlencode({key:value,key:value})
resultHtml = urllib.urlopen('[API or 网址]',params)
result = resultHtml.read()
print result


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.