我在Vala应用程序中使用libsoup从Instagram API获取数据。但是从它加载一页需要大约10秒钟(而浏览器在~1-2秒内显示相同的页面)。我最初认为这是因为HTTPS(HTTPS页面加载的方式比HTTP页面更长),但我发现大多数时候它解析得最多。
所以,问题是:我是否有任何方法可以在每次需要连接时将DNS结果缓存到不解析主机?或者有可能吗?
以下是我使用的功能:
public string getResponse (string host)
{
var session = new Soup.Session ();
session.ssl_strict = false;
session.user_agent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36";
var message = new Soup.Message ("GET", host);
message.tls_errors = GLib.TlsCertificateFlags.VALIDATE_ALL;
message.network_event.connect((event) => {
if (event == SocketClientEvent.RESOLVING) print("RESOLVING\n");
if (event == SocketClientEvent.RESOLVED) print("RESOLVED\n");
if (event == SocketClientEvent.CONNECTING) print("CONNECTING\n");
if (event == SocketClientEvent.CONNECTED) print("CONNECTED\n");
if (event == SocketClientEvent.PROXY_NEGOTIATING) print("PROXY_NEGOTIATING\n");
if (event == SocketClientEvent.PROXY_NEGOTIATED) print("PROXY_NEGOTIATED\n");
if (event == SocketClientEvent.TLS_HANDSHAKING ) print("TLS_HANDSHAKING \n");
if (event == SocketClientEvent.TLS_HANDSHAKED) print("TLS_HANDSHAKED\n");
if (event == SocketClientEvent.COMPLETE) print("COMPLETE\n");
});
print("start sending\n");
session.send_message (message);
print("stop sending\n");
return (string) message.response_body.data;
}
并且大部分时间都是在#34;解决之间"和#34;已解决。
顺便说一下,我认为在GSettings中设置一些字段以存储Instagram API服务器IP并将主机的主机名替换为该IP地址是个好主意,这会有用吗?如果它会,如何实现它?
答案 0 :(得分:1)
我用这种方式重写了我的getResponse函数,现在它按照我想要的方式工作。
public string getResponse (string host)
{
var ip = loadAddress();
if (ip == "")
ip = resolveHost();
var newHost = replaceHostWithIp(host, ip);
var session = new Soup.Session ();
session.ssl_strict = false;
session.user_agent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36";
var message = new Soup.Message ("GET", newHost);
message.tls_errors = GLib.TlsCertificateFlags.VALIDATE_ALL;
message.request_headers.append("Host", "api.instagram.com");
session.send_message (message);
if (loadAddress() == "")
setAddress(ip);
return (string) message.response_body.data;
}
其中loadAddress()
和setAddress()
是从GSettings加载IP并设置它的函数,replaceHostWithIp()
是用给定IP地址替换api.instagram.com
的函数。