如何在python中发出发布请求 [英] how to make post request in python

查看:140
本文介绍了如何在python中发出发布请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是curl命令:

curl -H "X-API-TOKEN: <API-TOKEN>" 'http://foo.com/foo/bar' --data # 

让我解释一下进入数据

POST /foo/bar
Input (request JSON body)

Name    Type    
title   string  
body    string

因此,基于此。我想通了:

So, based on this.. I figured:

curl -H X-API-TOKEN:' http://foo.com/foo/bar '--data'{ title: foobar, body:此主体同时具有双引号和单引号 }'

curl -H "X-API-TOKEN: " 'http://foo.com/foo/bar' --data '{"title":"foobar","body": "This body has both "double" and 'single' quotes"}'

不幸的是,我也无法弄清楚(例如cli的curl)
尽管我想使用python来发送此请求。
我该怎么做?

Unfortunately, I am not able to figure that out as well (like curl from cli) Though I would like to use python to send this request. How do i do this?

推荐答案

使用标准Python httplib urllib 库可以执行

With the standard Python httplib and urllib libraries you can do

import httplib, urllib

headers = {'X-API-TOKEN': 'your_token_here'}
payload = "'title'='value1'&'name'='value2'"

conn = httplib.HTTPConnection("heise.de")
conn.request("POST", "", payload, headers)
response = conn.getresponse()

print response

或者如果您想使用名为请求

or if you want to use the nice HTTP library called "Requests".

import requests

headers = {'X-API-TOKEN': 'your_token_here'}
payload = {'title': 'value1', 'name': 'value2'}

r = requests.post("http://foo.com/foo/bar", data=payload, headers=headers)

这篇关于如何在python中发出发布请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆