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()
print response.status, response.reason
302 Found
data = response.read()
data
'Redirecting to <a href="http://bugs.python.org/issue12524">http://bugs.python.org/issue12524</a>'
conn.close()
그런데 PHP로 어떻게 사용하는지, 파라암 변수 안에 있는 모든 것이 무엇인지, 어떻게 사용하는지 이해가 안 된다.이 일이 잘 되도록 내가 좀 도와줘도 될까?
Python을 사용하여 HTTP로 처리하려면 Requests: HTTP for Humanes를 적극 권장한다.질문에 적응한 POST 빠른 시작은 다음과 같다.
>>> import requests
>>> r = requests.post("http://bugs.python.org", data={'number': 12524, 'type': 'issue', 'action': 'show'})
>>> print(r.status_code, r.reason)
200 OK
>>> print(r.text[:300] + '...')
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>
Issue 12524: change httplib docs POST example - Python tracker
</title>
<link rel="shortcut i...
>>>
외부 pip 의존성이 없는 솔루션이지만 Python 3+에서만 작동(Python 2는 작동하지 않음):
from urllib.parse import urlencode
from urllib.request import Request, urlopen
url = 'https://httpbin.org/post' # Set destination URL here
post_fields = {'foo': 'bar'} # Set POST fields here
request = Request(url, urlencode(post_fields).encode())
json = urlopen(request).read().decode()
print(json)
샘플 출력:
{
"args": {},
"data": "",
"files": {},
"form": {
"foo": "bar"
},
"headers": {
"Accept-Encoding": "identity",
"Content-Length": "7",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "Python-urllib/3.3"
},
"json": null,
"origin": "127.0.0.1",
"url": "https://httpbin.org/post"
}
다음을 사용하여 POST 요청을 수행할 수 없음urllib
(GET에만 해당), 대신 모듈을 사용해 보십시오. 예:
예제 1.0:
import requests
base_url="www.server.com"
final_url="/{0}/friendly/{1}/url".format(base_url,any_value_here)
payload = {'number': 2, 'value': 1}
response = requests.post(final_url, data=payload)
print(response.text) #TEXT/HTML
print(response.status_code, response.reason) #HTTP
예 1.2:
>>> import requests
>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.post("http://httpbin.org/post", data=payload)
>>> print(r.text)
{
...
"form": {
"key2": "value2",
"key1": "value1"
},
...
}
예 1.3:
>>> import json
>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}
>>> r = requests.post(url, data=json.dumps(payload))
사용하다requests
라이브러리: REST API 끝점을 눌러 GET, POST, PUT, PUT 또는 DELETE.나머지 API 끝점 URL 전달url
, payload(payload) 인data
그리고 머리글/머리글 삽입headers
import requests, json
url = "bugs.python.org"
payload = {"number": 12524,
"type": "issue",
"action": "show"}
header = {"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain"}
response_decoded_json = requests.post(url, data=payload, headers=header)
response_json = response_decoded_json.json()
print(response_json)
데이터 사전은 양식 입력 필드의 이름을 기준으로 하며, 결과를 찾기 위해 해당 값을 올바르게 유지하십시오.양식 보기 헤더는 선언하는 데이터 유형을 검색하도록 브라우저를 구성한다.요청 라이브러리를 사용하면 POST:
import requests
url = "https://bugs.python.org"
data = {'@number': 12524, '@type': 'issue', '@action': 'show'}
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept":"text/plain"}
response = requests.post(url, data=data, headers=headers)
print(response.text)
요청 개체에 대한 자세한 정보: https://requests.readthedocs.io/en/master/api/
모듈을 사용하지 않으려면 다음과 같이 설치해야 한다.requests
, 그리고 당신의 사용 케이스는 매우 기본적이고, 그러면 당신은 사용할 수 있다.urllib2
urllib2.urlopen(url, body)
자세한 내용은 설명서를 참조하십시오.urllib2
https://docs.python.org/2/library/urllib2.html.
요청 라이브러리를 사용하여 사후 요청을 할 수 있다.페이로드에 JSON 문자열이 있으면 예상 페이로드 형태인 json.dumps(페이로드)를 사용할 수 있다.
import requests, json
url = "http://bugs.python.org/test"
payload={
"data1":1234,'data2':'test'
}
headers = {
'Content-Type': 'application/json'
}
response = requests.post(url, headers=headers, data=json.dumps(payload))
print(response.text , response.status_code)
참조URL: https://stackoverflow.com/questions/11322430/how-to-send-post-request
'IT이야기' 카테고리의 다른 글
개체의 특성 나열 (0) | 2022.03.17 |
---|---|
React Native 프로젝트에서 어떤 폴더를 선택하십시오. (0) | 2022.03.17 |
VueRouter는 URL을 변경하지만 구성 요소는 변경하지 않음 (0) | 2022.03.17 |
이 오류를 해결하는 방법: " 모듈을 찾을 수 없음: popper.js "을(를) 확인할 수 없음 (0) | 2022.03.16 |
Vuetify에서 수직으로 컨텐츠 중앙 집중 (0) | 2022.03.16 |