Post request by QWebEngineHttpRequest (PyQt5)

Tags: , , , ,



I have a question about making POST request in PyQt5. Unfortunately official documentation for this framework for Python doesen’t exist. I have to translate docs from C++ to Python.

I have a problem with handle it. To make POST request I have to create instance of class QWebEngineHttpRequest (docs), and then add POST data by setPostData(), it looks to be easy, but that method requires a parameter in type QByteArray (docs), and here is a problem because i don’t know how to insert data into this.

Answer

I know I’m late, but I hope it helps someone else with the same issue. Here’s how I’ve done it:

def postRequest(self):
    self.url = QUrl()
    self.req = QWebEngineHttpRequest()

    self.url.setScheme("http")
    self.url.setHost("stackoverflow")
    self.url.setPath("/something/somethingelse")

    self.req.setUrl(self.url)
    self.req.setMethod(QWebEngineHttpRequest.Post)
    self.req.setHeader(QByteArray(b'Content-Type'),QByteArray(b'application/json'))

    params = {"something": value, "test": True, "number": 5}

    self.req.setPostData(bytes(json.dumps(params), 'utf-8')) 
    
    return self.req


Source: stackoverflow