用Python發生RestFul API POST和GET請求


使用Python調Restful API

本文給出用GET方法從Restful API獲取信息和用POST方法向Restful API發生消息。主要使用的包是urllib和json,其中urllib用來發送http請求,json包用來解析和構造json數據。具體例子如下:

通過GET方法獲取信息

import json
from urllib import request

query_url_addr='' #the Restful api url
query_headers={'cookie':'the cooke'} #the request headers
req = request.Request(query_url_addr, headers=query_headers)
resp = request.urlopen(req)
result = resp.read().decode()
result_json = json.loads(result)#the json object of response data

用POST方法向Restful API發生消息

import json
import time
from urllib import request
from urllib import error
try:
    create_url=''#the create request url
    create_headers={'cookie':'the cooke'} #the request headers
    body_data_str='{"body":"bodytext"}'
    body_data = bytes(body_data_str, 'utf8')
    req = request.Request(create_url, headers=create_headers, data=body_data, method='POST')
    resp = request.urlopen(req)
    result = resp.read().decode()
    result_json = json.loads(result)
    return result_json
except error.HTTPError as err:
     error_body = err.file.read().decode()
     return  json.loads(result)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM