以下是一个使用Python编写的代码示例,用于调用API并返回HTTP代码:
import requests
def get_http_code(api_url):
response = requests.get(api_url)
return response.status_code
api_url = "https://example.com/api"
http_code = get_http_code(api_url)
print("HTTP Code:", http_code)
在此示例中,我们使用了Python的requests
库来发送GET请求并获取API的响应。get_http_code
函数接受一个API的URL作为参数,并返回HTTP代码。在主程序中,我们将API的URL传递给get_http_code
函数,并将返回的HTTP代码打印出来。
请注意,此示例假设API的URL是有效的,并且可以成功访问。如果API无法访问或返回错误,代码示例可能需要进一步处理错误情况。