2012-07-04 24 views
134

Ho trovato questo script on-line:Come inviare la richiesta POST?

import httplib, urllib 
params = urllib.urlencode({'number': 12524, 'type': 'issue', 'action': 'show'}) 
headers = {"Content-type": "application/x-www-form-urlencoded", 
      "Accept": "text/plain"} 
conn = httplib.HTTPConnection("bugs.python.org") 
conn.request("POST", "", params, headers) 
response = conn.getresponse() 
print response.status, response.reason 
302 Found 
data = response.read() 
data 
'Redirecting to <a href="http://bugs.python.org/issue12524">http://bugs.python.org/issue12524</a>' 
conn.close() 

Ma io non capisco come usarlo con PHP o che cosa tutto dentro la variabile params è o come usarlo. Posso avere un piccolo aiuto per cercare di farlo funzionare?

+1

La richiesta di posta è solo una richiesta di posta, indipendentemente dal lato server. –

+7

Invia una richiesta POST. Quindi il server risponde con 302 (reindirizzamenti) intestazioni al tuo POST. Cosa c'è di sbagliato? – ddinchev

+1

Questo script non sembra python3.2 compat – jdi

risposta

214

Se si vuole veramente gestire con HTTP usando Python, consiglio vivamente lo Requests: HTTP for Humans. Il POST quickstart adattato alla tua domanda è:

>>> import requests 
>>> r = requests.post("http://bugs.python.org", data={'number': 12524, 'type': 'issue', 'action': 'show'}) 
>>> print(r.status_code, r.reason) 
200 OK 
>>> print(r.text[:300] + '...') 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 
<head> 
<title> 
Issue 12524: change httplib docs POST example - Python tracker 

</title> 
<link rel="shortcut i... 
>>> 
+0

Non riesco a ottenere lo stesso risultato come hai fatto sopra. Ho scritto un altro numero di problema sulla pagina e poi ho eseguito lo script ma non sono riuscito a vedere il numero di problema sul risultato. –

+1

Si prega di cambiare dati = {'numero': 12524, per leggere i dati = {'numero': '12524' ,. L'avrei modificato io stesso ma le modifiche devono essere più di 6 caratteri. Grazie per il record – kevthanewversi

+0

: un codice funzionante per me, data = {'@ number': '12524', '@type': 'issue', '@action': 'show'} – marr

15

Non è possibile ottenere le richieste POST utilizzando urllib (solo per GET), invece provare a utilizzare il modulo requests, ad esempio:

Esempio 1.0:

import requests 

base_url="www.server.com" 
final_url="/{0}/friendly/{1}/url".format(base_url,any_value_here) 

payload = {'number': 2, 'value': 1} 
response = requests.post(final_url, data=payload) 

print(response.text) #TEXT/HTML 
print(response.status_code, response.reason) #HTTP 

Esempio 1.2:

>>> import requests 

>>> payload = {'key1': 'value1', 'key2': 'value2'} 

>>> r = requests.post("http://httpbin.org/post", data=payload) 
>>> print(r.text) 
{ 
    ... 
    "form": { 
    "key2": "value2", 
    "key1": "value1" 
    }, 
    ... 
} 

Esempio 1.3:

>>> import json 

>>> url = 'https://api.github.com/some/endpoint' 
>>> payload = {'some': 'data'} 

>>> r = requests.post(url, data=json.dumps(payload)) 
81

Se è necessario lo script per essere portatile e non preferisce avere dipendenze 3a parte, questo è il modo di inviare richiesta POST puramente in Python 3.

from urllib.parse import urlencode 
from urllib.request import Request, urlopen 

url = 'https://httpbin.org/post' # Set destination URL here 
post_fields = {'foo': 'bar'}  # Set POST fields here 

request = Request(url, urlencode(post_fields).encode()) 
json = urlopen(request).read().decode() 
print(json) 

Esempio di output:

{ 
    "args": {}, 
    "data": "", 
    "files": {}, 
    "form": { 
    "foo": "bar" 
    }, 
    "headers": { 
    "Accept-Encoding": "identity", 
    "Content-Length": "7", 
    "Content-Type": "application/x-www-form-urlencoded", 
    "Host": "httpbin.org", 
    "User-Agent": "Python-urllib/3.3" 
    }, 
    "json": null, 
    "origin": "127.0.0.1", 
    "url": "https://httpbin.org/post" 
} 
+6

Questo codice funzionerà solo in Python 3, come ho detto nella risposta. – stil

Problemi correlati