2016-09-28 85 views
0

我知道這看起來很基本,但我們該怎麼做呢?例如,通過POST發送長JSON Python

import urllib2 
import ssl 
import requests 
import json 

SetProxy={'https':'https://sample.sample.com'} 
proxy = urllib2.ProxyHandler(SetProxy) 
url="https://something.com/getsomething" 
opener = urllib2.build_opener(proxy) 
urllib2.install_opener(opener) 
payload = { 
    "uaaURL": "https://com-example.something.com", 
    "sampleID": "admin", 
    "sampleSecret": "password", 
    "sampleID2": "example-sample-el", 
    "sampleSecret2": "ssenjsoemal/+11=", 
    "username": "test", 
    "someAttributes": { 
    "Groups": [ 
     "example_com-abc" 
    ], 
    "attribute": [ 
     "value1" 
    ] 
    } 
} 

req = urllib2.Request(url) 
req.add_header('Content-Type','application/json') 
response = urllib2.urlopen(req, json=json.dumps(payload)) 

以上運行並給了我一個400這意味着我的JSON是壞的。我無法找到通過發佈請求發送大量JSON數據的帖子。有什麼建議?謝謝!

+0

你如何你的API在處理這個? 400通常意味着JSON根據API規範是無效的。 –

+0

JSON格式應完全符合我分配給我的有效負載(空格和全部)的格式。然後API接受它。 –

回答

-1

嘗試以下使用方法:

import json 

import urllib2 

import ssl 

import requests 

SetProxy={'https':'https://sample.sample.com'} 

proxy = urllib2.ProxyHandler(SetProxy) 

url='https://something.com/getsomething' 

opener = urllib2.build_opener(proxy) 

urllib2.install_opener(opener) 

data = { 
    'uaaURL' : 'https://com-example.something.com', 
    'sampleID': 'admin', 
    'sampleSecret': 'password', 
    'sampleID2': 'example-sample-el', 
    'sampleSecret2': 'ssenjsoemal/+11=', 
    'username': 'test', 
    'someAttributes': { 
    'Groups': ['example_com-abc' ], 
    'attribute': [ 'value1' ] 
    } 

req = urllib2.Request('https://something.com/getsomething') 

req.add_header('Content-Type', 'application/json') 

response = urllib2.urlopen(req, json.dumps(data)) 
+0

不起作用。雙引號是API的期望。 –

+0

好的,然後用雙引號試試這個 –

+0

你做了什麼改變?我找不到變化? –