2012-03-17 20 views
76
data = { 
     'ids': [12, 3, 4, 5, 6 , ...] 
    } 
    urllib2.urlopen("http://abc.com/api/posts/create",urllib.urlencode(data)) 

Desidero inviare una richiesta POST, ma uno dei campi deve essere un elenco di numeri. Come lo posso fare ? (JSON?)Come si invia una richiesta POST come JSON?

+1

Non è che già un elenco di numeri, però? –

+0

Non è possibile rispondere a questa domanda senza sapere quale tipo di input si aspetta l'API. –

+0

La mia API si aspetta un elenco. – TIMEX

risposta

124

Se il server è in attesa della richiesta POST di essere JSON, allora si avrebbe bisogno di aggiungere un'intestazione, e anche serializzare i dati per la vostra richiesta ...

import json 
import urllib2 

data = { 
     'ids': [12, 3, 4, 5, 6] 
} 

req = urllib2.Request('http://example.com/api/posts/create') 
req.add_header('Content-Type', 'application/json') 

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

Se don 't specificare l'intestazione, sarà il tipo predefinito application/x-www-form-urlencoded.

+0

Ho una domanda. è possibile aggiungere più elementi nell'intestazione ... come tipo di contenuto e id-cliente ... @jdi –

+0

@OmarJandali, basta chiamare di nuovo 'add_header()', per ogni intestazione che si desidera aggiungere. – jdi

+0

Ho il seguente codice ma non stampa nulla. doveva stampare l'url e le intestazioni, ma non è stato stampato nulla ... 'req = urllib.Request ('http://uat-api.synapsefi.com') req.add_header ('X-SP-GATEWAY', 'client_id_asdfeavea561va9685e1gre5ara | client_secret_4651av5sa1edgvawegv1a6we1v5a6s51gv') req.add_header ('X-SP-USER-IP', '127.0.0.1') req.add_header ('X-SP-UTENTE', '| ge85a41v8e16v1a618gea164g65') req.add_header ('Content-Type', 'application/json') print (req) '... –

86

Si consiglia di utilizzare l'incredibile modulo requests.

http://docs.python-requests.org/en/v0.10.7/user/quickstart/#custom-headers

url = 'https://api.github.com/some/endpoint' 
payload = {'some': 'data'} 
headers = {'content-type': 'application/json'} 

response = requests.post(url, data=json.dumps(payload), headers=headers) 
+0

Questo mi dà "TypeError: post() prende da 1 a 2 argomenti posizionali ma 3 sono stati dati" – zakdances

+8

The [ultima API] (http://docs.python-requests.org/en/latest/api /) sembra avere un parametro 'json' in modo da poter escludere' import json' e 'json.dumps()' –

4

si deve aggiungere un'intestazione, o avrete HTTP 400 errore. Il codice funziona bene su python2.6, centos5.4

codice:

import urllib2,json 

    url = 'http://www.google.com/someservice' 
    postdata = {'key':'value'} 

    req = urllib2.Request(url) 
    req.add_header('Content-Type','application/json') 
    data = json.dumps(postdata) 

    response = urllib2.urlopen(req,data) 
27

per Python 3.4.2 ho trovato il seguente funzionerà:

 import urllib.request 
    import json  

    body = {'ids': [12, 14, 50]} 

    myurl = "http://www.testmycode.com" 
    req = urllib.request.Request(myurl) 
    req.add_header('Content-Type', 'application/json; charset=utf-8') 
    jsondata = json.dumps(body) 
    jsondataasbytes = jsondata.encode('utf-8') # needs to be bytes 
    req.add_header('Content-Length', len(jsondataasbytes)) 
    print (jsondataasbytes) 
    response = urllib.request.urlopen(req, jsondataasbytes) 
+0

Python3.6.2 questo ha funzionato. Solo l'aggiunta di intestazione con req.add_header (...) ha funzionato per me. –

2

Questo funziona perfetto per Python Versione 3.5, Se l'URL contiene valore String/Parametro query,

URL richiesta = https://bah2.com/ws/rest/v1/concept/

Valore parametro = 21f6bb43-98a1-419d-8f0c-8133669e40ca

import requests 
r = requests.post('https://bah2.com/ws/rest/v1/concept/21f6bb43-98a1-419d-8f0c-8133669e40ca',auth=('username', 'password'),verify=False, json={"name": "Value"}) 
headers = {'Content-type': 'application/json'} 
print(r.status_code) 
+4

nel tuo snipper di codice, la variabile delle intestazioni rimane inutilizzata – shookees

Problemi correlati