Django用标题创建/发出POST请求

时间:2013-06-20 06:39:04

标签: django http-headers http-post google-url-shortener

我想以编程方式使用自定义标头发出POST请求。我怎么能这样做?

实际上我正在尝试this;使用google shortener api。也许我误解了:/

提前感谢您:)

3 个答案:

答案 0 :(得分:10)

answer工作得很好。但找到了另一个solution;

import requests
import json

url = 'https://www.googleapis.com/urlshortener/v1/url'
data = {'longUrl': 'http://www.google.com/'}
headers = {'Content-Type': 'application/json'}

r = requests.post(url, data=json.dumps(data), headers=headers)

然后

answer = json.loads(r.text)

answer = r.json()

这是requests包; codedoc

答案 1 :(得分:5)

要使用Python发送POST请求并使用标题,您可以执行类似

的操作
import urllib2
import json
data = {'data':'data'}
url = api_url
opener = urllib2.build_opener(urllib2.HTTPHandler)
request = urllib2.Request(url, data=json.dumps(data))
request.add_header("Content-Type", "application/json") #Header, Value                                        
opener.open(request)

答案 2 :(得分:0)

import json
import requests
def short_url(url):
    post_url = 'https://www.googleapis.com/urlshortener/v1/url?key={API_KEY}'
    params = json.dumps({'longUrl': url})
    response = requests.post(post_url,params,headers={'Content-Type': 'application/json'})
    return response.json()['id']