MST

星途 面试题库

面试题:Python网络应用开发之HTTP请求处理

在Python的网络应用开发中,使用requests库发送一个带认证信息和自定义头部的HTTP POST请求,将数据 {'key': 'value'} 发送到指定URL 'http://example.com/api',并处理可能出现的异常,最后返回响应的状态码和内容,写出完整代码。
30.2万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
import requests


def send_post_request():
    url = 'http://example.com/api'
    data = {'key': 'value'}
    headers = {
        'Custom-Header': 'SomeValue'
    }
    auth = ('username', 'password')

    try:
        response = requests.post(url, data=data, headers=headers, auth=auth)
        response.raise_for_status()
        return response.status_code, response.text
    except requests.exceptions.RequestException as e:
        print(f"请求发生异常: {e}")
        return None, None


status_code, content = send_post_request()
if status_code is not None:
    print(f"状态码: {status_code}")
    print(f"内容: {content}")