天天看點

python3調用http接口

最近在寫python調用接口的服務,寫了一個調用接口的函數,如下:

import http.client
import json

def call_api(inputdata, url):
    """
    :param inputdata: 單個樣本的輸入參數,是json格式的資料
    :return: 單個樣本的探真查詢變量結果資料
    """
    # 調用接口
    connection = http.client.HTTPConnection(url)
    headers = {'Content-type': 'application/json'}
    json_foo = json.dumps(inputdata)
    connection.request('POST', '/XXXX/XXXX', json_foo, headers)
    response = connection.getresponse()
    res = json.loads(response.read().decode())
    # 接口有正确的資料才讀入,否則為空
    if res['code'] == '0000':
        res_data = json.loads(res['data'])
    else:
        res_data = {}
    return res_data
           

url 是形如 ‘xxx.xxx.xxx.xx:xxxx’。

http子產品簡介 http.client 是一個底層的 HTTP 協定用戶端,被更高層的 urllib.request 子產品所使用。

http.client 子產品 http.client 子產品定義了實作 http 和 https 協定用戶端的類。該子產品通常不會直接使用,而是用封裝好的 urllib.request 子產品來使用他們處理 URL 。

HTTPConnection 類 初始化一個http連結。

HTTPConnection 執行個體表示與 HTTP 伺服器的事務。

HTTPConnection 對象方法 request請求的方法和請求的連結位址。

使用指定的 method 方法和 url 連結向伺服器發送請求。 如果指定 了body 部分,那麼 body 部分将在 header 部分發送完之後發送過去。body 部分可以是一個字元串、位元組對象、檔案對象或者是位元組對象的疊代器。不同的 body 類型對應不同的要求。header 參數應該是 HTTP 頭部的映射,是一個字典類型。post 請求資料的headers參數要帶上 Content-type 字段,以告知消息主體以何種方式編碼。

HTTPConnection.getresponse() 得到傳回的http response。必須在請求發送後才能調用得到伺服器傳回的内容,傳回的是一個 HTTPResponse 執行個體。

urllib.request調用接口的方式

import  urllib.request
import json

#以post方式送出指令
postdata = urllib.parse.urlencode(params).encode('utf-8')
json.loads(urllib.request.urlopen(api_url, postdata, timeout=HTTP_TIME_OUT).read().decode('utf-8'))
           

建議參考:

Python3 内置http.client,urllib.request及三方庫requests發送請求對比: https://www.jianshu.com/p/491d6590b2a0