1. 程式人生 > >Python POST Json資料到Http

Python POST Json資料到Http

》安裝Python

》cmd terminal 安裝requests模組,command: pip install requests

》Python 指令碼:此列是post “json.json”的樣本到“url ”

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib2
import urllib
import cookielib
import json
import httplib
import re
import requests
s=requests.session()
headers = {'Content-Type':'application/json'}
url = 'http://localhost:7654/hermes/command'   #Post url
fo = open("C:\Json_Post\json.json","rb")  #需要post的json資料
values = fo.read()
try:
r = s.post(url,data=values,headers = headers)
except BaseException:
print"Error:connection"
else:
print r.text
fpost = open("C:\Json_Post\Post\post_result.txt","w")
fpost.write(r.text)
fpost.close()