반응형
urlib2 및 json
JSON 형식의 데이터로 urlib2를 사용하여 POST 요청을 수행하는 방법을 보여주는 튜토리얼을 지적해 주실 수 있습니까?
Messa의 답변은 서버가 content-type 헤더를 굳이 확인하지 않을 때만 작동합니다.실제로 작동하려면 content-type 헤더를 지정해야 합니다.다음은 콘텐츠 유형 헤더를 포함하도록 수정된 Messa의 답변입니다.
import json
import urllib2
data = json.dumps([1, 2, 3])
req = urllib2.Request(url, data, {'Content-Type': 'application/json'})
f = urllib2.urlopen(req)
response = f.read()
f.close()
Urlib가 Content-Length를 계산하기 위해 사용하는 것이 무엇이든 json에 의해 혼동되는 것 같기 때문에 직접 계산해야 합니다.
import json
import urllib2
data = json.dumps([1, 2, 3])
clen = len(data)
req = urllib2.Request(url, data, {'Content-Type': 'application/json', 'Content-Length': clen})
f = urllib2.urlopen(req)
response = f.read()
f.close()
이걸 알아내는 데 오래 걸렸어 그러니 다른 사람에게 도움이 됐으면 좋겠어
예 - JSON으로 인코딩된 일부 데이터를 POST 데이터로 전송합니다.
import json
import urllib2
data = json.dumps([1, 2, 3])
f = urllib2.urlopen(url, data)
response = f.read()
f.close()
json 반응을 읽는 방법json.loads()
여기 샘플이 있습니다.
import json
import urllib
import urllib2
post_params = {
'foo' : bar
}
params = urllib.urlencode(post_params)
response = urllib2.urlopen(url, params)
json_response = json.loads(response.read())
헤더를 해킹하여 적절한 Ajax Request를 얻어야 합니다.
headers = {'X_REQUESTED_WITH' :'XMLHttpRequest',
'ACCEPT': 'application/json, text/javascript, */*; q=0.01',}
request = urllib2.Request(path, data, headers)
response = urllib2.urlopen(request).read()
To json.는 서버 측에서 POST를 로드합니다.
Edit : 그런데 보내기 전에 편집해야 합니다.그렇지 않으면 POST는 서버가 예상한 대로 되지 않습니다.
이것이 나에게 효과가 있었다.
import json
import requests
url = 'http://xxx.com'
payload = {'param': '1', 'data': '2', 'field': '4'}
headers = {'content-type': 'application/json'}
r = requests.post(url, data = json.dumps(payload), headers = headers)
언급URL : https://stackoverflow.com/questions/3290522/urllib2-and-json
반응형
'sourcecode' 카테고리의 다른 글
발신기지 'Authorization' 헤더와 jquery.ajax()의 교차 발신 (0) | 2023.03.09 |
---|---|
ASP.net MVC에서 JSONP 반환 (0) | 2023.03.09 |
react render()가 componentDidMount()보다 먼저 호출되고 있습니다. (0) | 2023.03.04 |
React.js에서 리치 데이터 구조 편집 (0) | 2023.03.04 |
AngularJS 형식 JSON 문자열 출력 (0) | 2023.03.04 |