2017-09-17 12 views
2

私はPythonを初めて使っています。 ヘッダと本文の詳細を使用してウェブサイトに認証リクエストを投稿する必要があります。 これまで私が持っていた以下のコードを掲載しました。実行すると、次の行に構文エラーが表示されます。ヘッダと本文でのpython投稿リクエストの構築方法

req.add_header('API-KEY': 'my_api_key', 'ACCOUNT-ID': 'my_account_id', 'Content-Type': 'application/json; charset=UTF-8', 'VERSION': '2') 

私が間違っている箇所を確認して教えてください。

import urllib.request 
import json 

body = {'identifier': 'my_id', 'password': 'my_encrypted_pwd', 'encryptedPassword': true} 

url = 'https://mywebsite.com/gateway/deal/session' 
req = urllib.request.Request(url) 
req.add_header('API-KEY': 'my_api_key', 'ACCOUNT-ID': 'my_account_id', 'Content-Type': 'application/json; charset=UTF-8', 'VERSION': '2') 
jsondata = json.dumps(body) 
jsondataasbytes = jsondata.encode('UTF-8') 
req.add_header('Content-Length', len(jsondataasbytes)) 
print (jsondataasbytes) 
response = urllib.request.urlopen(req, jsondataasbytes) 

答えて

1

私はそれが高速ですし、単にurllib.requestよりも良いようあなたは、requestsモジュールを使用する必要がありますお勧め:

response = requests.put(
     url, 
     body, headers={'API-KEY': 'my_api_key', 
         'ACCOUNT-ID': 'my_account_id', 
         'Content-Type': 'application/json; charset=UTF-8', 
         'VERSION': '2' 
       } 
     ) 

今、あなたはresponseあなたがいつものように取得を解析することができます。

関連する問題