以下是一个使用Python编写的并发HTTP请求采样器示例,可以动态添加URL:
import requests
import threading
# 定义一个全局变量,用于存储所有的URL结果
results = []
def send_request(url):
response = requests.get(url)
results.append(response.text)
def concurrent_requests(urls):
threads = []
for url in urls:
thread = threading.Thread(target=send_request, args=(url,))
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
# 打印所有URL的结果
for result in results:
print(result)
if __name__ == "__main__":
urls = ["http://example.com", "http://google.com", "http://github.com"]
concurrent_requests(urls)
在上面的示例中,我们使用了Python的requests
库来发送HTTP请求,并使用多线程来实现并发。我们首先定义了一个全局变量results
,用于存储所有URL的结果。然后,我们定义了一个send_request
函数,用于发送HTTP请求并将结果添加到results
中。接下来,我们定义了一个concurrent_requests
函数,它接受一个URL列表作为参数,并使用多线程来并发发送请求。最后,我们在main
函数中调用concurrent_requests
函数,并传入URL列表。
当我们运行这个示例时,它将同时发送多个HTTP请求,并将每个URL的结果打印出来。你可以根据需要自行修改代码,以适应你的具体需求。