2017-08-23 13 views
0

私はpython3.6.2でHTTP(Webはhttps)のPostフィールドを必要とするWeb APIを使用しようとしています。 私がurllib.request.urlopen試してみましたが、応答はここHTTP投稿をPythonでurllibとリクエストを使用して

urllib.error.HTTPError: HTTP Error 403: Forbidden

だった私が使用するコードです:

from urllib.parse import urlencode 
from urllib.request import Request, urlopen 
from hashlib import sha256 
import time 

key = 'xxxxxxxxxx' 
secret_key = 'yyyyyyyyyyyy' 
nonce = int(time.time()) 

signature = sha256((key + str(nonce) + secret_key).encode()).hexdigest() 

url = "https://xxxxx/api/" 
post_fields = {'key': key, 'nonce': nonce, 
       'signature': signature} 

request = Request(url, data=urlencode(post_fields).encode()) 
response = urlopen(request).read().decode() 

私はこのコードでrequests libraryを試してみましたが:

import requests 
from hashlib import sha256 
import time 

key = 'xxxxxxxxxx' 
secret_key = 'yyyyyyyyyyyy' 
nonce = int(time.time()) 

signature = sha256((key + str(nonce) + secret_key).encode()).hexdigest() 

url = "https://xxxxx/api/" 
post_fields = {'key': key, 'nonce': nonce, 
         'signature': signature} 
response = requests.post(url, post_fields) 

をそれは動作します。 データのパラメータが指定されている場合、urllib.requestはpost要求を送信できるので、私は実際に異なることを知りたいです。

答えて

1

両方のスニペットコードが正しいPOSTリクエストを送信します。それらの間の唯一の違いは、どのヘッダーが送信されるかです。別に全く同じでヘッダから、urllib.requestがお送りします:

Accept-Encoding: identity 
User-Agent: Python-urllib/3.6 

requestsながらがお送りします:

Accept: */* 
Accept-Encoding: gzip, deflate 
User-Agent: python-requests/2.18.1 

あなたが追加して見るためにあなたのurllib.requestコードにヘッダを変更することで実験する必要があると思いますそれらが問題ならば。

投稿した情報を確認するには、いつでもURLとしてhttp://httpbin.org/postを使用できます。そのサービスはJSONオブジェクトとして受け取ったものをエコーバックします。詳細については、http://httpbin.orgを参照してください。

+0

キーパラメータに変更しました(実際の変数名を表示したくない)。 urllib.requestによって送信されたヘッダーを変更しようとします。 あなたの答えをありがとう。 –

関連する問題