我想使用libSoup GLib库向https://httpbin.org/get
发出一个简单的HTTP GET请求,在python中使用GObject-introspection(gi)。
你是怎么做到的?
答案 0 :(得分:2)
这是一个发出请求并打印出响应的示例:
import sys
import gi
gi.require_version('Soup', '2.4')
from gi.repository import Gio, Soup
session = Soup.Session()
uri = Soup.URI.new('https://httpbin.org/get')
request = session.request_http_uri('GET', uri)
stream = request.send(cancellable=None)
out = Gio.UnixOutputStream(fd=sys.stdout.fileno())
out.splice(stream, Gio.OutputStreamSpliceFlags.CLOSE_SOURCE, cancellable=None)
答案 1 :(得分:1)
这是部分异步的版本,可以进行改进(特别是将结果放入python变量中)。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import gi
gi.require_version('Soup', '2.4')
from gi.repository import Soup, GLib, Gio
class HttpClient:
def __init__(self):
self.session = Soup.Session()
def get(self, uri):
print("Opening %s" % uri)
message = Soup.Message.new("GET", uri)
self.session.send_async(message, None, self.on_finished, message)
def on_finished(self, session, result, message):
input_stream = session.send_finish(result)
status_code = message.status_code
print(status_code)
if input_stream:
data_input_stream = Gio.DataInputStream.new(input_stream)
lines = list()
while True:
line, length = data_input_stream.read_line_utf8()
if line is None:
print("Finished")
break
else:
lines.append(line)
page = "".join(lines)
print(page)
if __name__ == '__main__':
c = HttpClient()
ml = GLib.MainLoop()
GLib.idle_add(c.get, "https://www.google.com")
ml.run()