QNetworkAccessManager是Qt自带的一个网络请求库,网上很多说的很模糊,在这总结一下
# coding: utf-8
import json
import sys
from pathlib import Path
from typing import Union
from urllib.parse import urlencodefrom PyQt5.QtNetwork import QNetworkRequest, QNetworkAccessManager, QNetworkReply, QHttpMultiPart, QHttpPart
from PyQt5.QtCore import QUrl, pyqtSignal, QByteArray, QJsonDocument, QCoreApplication, QObject, QFile, QIODeviceclass NetworkRequestsManager(QObject):finished = pyqtSignal(QNetworkReply)def __init__(self, parent=None, *, encoding='utf-8'):super().__init__(parent)self._reply = None # type: QNetworkReplyself._encoding = encodingself.networkAccessManager = QNetworkAccessManager(parent)self.networkAccessManager.finished.connect(self.finished)def get(self, url: Union[str, QUrl], params=None, headers=None):request = QNetworkRequest(self.__initUrl(url, params))self.__initHeaders(request, headers)self.networkAccessManager.get(request)def post(self, url: Union[str, QUrl], params: dict = None, json: dict = None, headers: dict = None):request = QNetworkRequest(self.__initUrl(url, params))self.__initHeaders(request, headers)self.networkAccessManager.post(request, self.__initJson(json))def file_post(self, url: Union[str, QUrl], file: dict, headers: dict = None):request = QNetworkRequest(self.__initUrl(url, params))multiPart = QHttpMultiPart(QHttpMultiPart.FormDataType)for item in file.items():httpPart = QHttpPart()file = QFile(item[1])file.open(QIODevice.ReadOnly)httpPart.setHeader(QNetworkRequest.ContentDispositionHeader,f'form-data; name="{item[0]}"; filename="{Path(item[1]).name}"')httpPart.setBodyDevice(file)file.setParent(multiPart)multiPart.append(httpPart)self.__initHeaders(request, headers)self.networkAccessManager.post(request, multiPart)def __initUrl(self, url: Union[str, QUrl], params: dict = None) -> QUrl:if isinstance(url, str):url = QUrl(url)url.setQuery(urlencode(params), QUrl.ParsingMode.TolerantMode)return urldef __initHeaders(self, request: QNetworkRequest, headers: dict = None):if headers is None:returnfor item in headers.items():request.setRawHeader(item[0].encode(), item[1].encode())def __initJson(self, json: dict = None):if json is None:returnreturn QJsonDocument(json).toJson()if __name__ == '__main__':# 这是一个联想壁纸的接口app = QCoreApplication(sys.argv)manager = NetworkRequestsManager()params = {"skip": "0","limit": "54","count": "76873","tagId": "-1","colorId": "-1","classId": "-1","refresh": "true","priceId": "0"}url = 'https://pc-store.lenovomm.cn/wallpapercontent/wallpaper/class_wallpaper_list'headers = {"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzbWJPcHRpb25zIjoiMSIsImJ1c2luZXNzS2V5IjoiIiwiY2hhbm5lbCI6IjIwMDA1IiwiZnJvbSI6ImluZHN0b3JlIiwidmVyc2lvbk5hbWUiOiI5LjAuMTMzMC4yMDEiLCJleHAiOjIzNDI4NjY3NzEsInZlcnNpb25Db2RlIjoiOS4wLjEzMzAuMjAxIn0.2_R46WPaT2BCy_NcbewdfosiSlLEMdNRX9cJIoqb6eY","user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36&PCStore"}manager.get(QUrl(url), params, headers=headers)def response(reply: QNetworkReply):if reply.error() == reply.NoError:print(json.loads(reply.readAll().data().decode('utf-8')))else:print(reply.errorString())manager.finished.connect(response)sys.exit(app.exec_())