본문 바로가기
파이썬

파이썬 Python3 : 요청 라이브러리없이 JSON POST 요청

by º기록 2020. 12. 10.
반응형

네이티브 Python 라이브러리 만 사용하여 JSON 인코딩 데이터를 서버로 보내고 싶습니다. 나는 요청을 좋아하지만 스크립트를 실행하는 컴퓨터에서 사용할 수 없기 때문에 단순히 사용할 수 없습니다. 나는 그것을없이해야합니다.

newConditions = {"con1":40, "con2":20, "con3":99, "con4":40, "password":"1234"} 
params = urllib.parse.urlencode(newConditions)
params = params.encode('utf-8')

req = urllib.request.Request(conditionsSetURL, data=params)
urllib.request.urlopen(req)        

내 서버는 로컬 WAMP 서버입니다. 나는 항상

urllib.error.HTTPError : HTTP 오류 500 : 내부 서버 오류

동일한 시스템에서 동일한 서버에서 동일한 URL을 사용하는 동일한 데이터가 요청과 함께 작동하므로 이것이 서버 문제가 아닌 100 % 입니다. 도서관과 우체부.

 

해결 방법

 

JSON을 게시하지 않고 application / x-www-form-urlencoded 요청을 게시하고 있습니다.

JSON으로 인코딩하고 올바른 헤더를 설정합니다.

import json

newConditions = {"con1":40, "con2":20, "con3":99, "con4":40, "password":"1234"} 
params = json.dumps(newConditions).encode('utf8')
req = urllib.request.Request(conditionsSetURL, data=params,
                             headers={'content-type': 'application/json'})
response = urllib.request.urlopen(req)

데모:

>>> import json
>>> import urllib.request
>>> conditionsSetURL = 'http://httpbin.org/post'
>>> newConditions = {"con1":40, "con2":20, "con3":99, "con4":40, "password":"1234"} 
>>> params = json.dumps(newConditions).encode('utf8')
>>> req = urllib.request.Request(conditionsSetURL, data=params,
...                              headers={'content-type': 'application/json'})
>>> response = urllib.request.urlopen(req)
>>> print(response.read().decode('utf8'))
{
  "args": {}, 
  "data": "{\"con4\": 40, \"con2\": 20, \"con1\": 40, \"password\": \"1234\", \"con3\": 99}", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Accept-Encoding": "identity", 
    "Connection": "close", 
    "Content-Length": "68", 
    "Content-Type": "application/json", 
    "Host": "httpbin.org", 
    "User-Agent": "Python-urllib/3.4", 
    "X-Request-Id": "411fbb7c-1aa0-457e-95f9-1af15b77c2d8"
  }, 
  "json": {
    "con1": 40, 
    "con2": 20, 
    "con3": 99, 
    "con4": 40, 
    "password": "1234"
  }, 
  "origin": "84.92.98.170", 
  "url": "http://httpbin.org/post"
}

 

참조 페이지 https://stackoverflow.com/questions/25491541

 

 

반응형

댓글