python使用urllib2通过http发送报文

本文提供了一个使用Python发送HTTP请求的示例代码,包括Python2和Python3版本的实现方式。通过具体的代码示例展示了如何构造请求头和请求体,并读取服务器返回的数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# -*- coding: utf-8 -*-
##python 2版本
import urllib2


# http发送报文
def httpsend(url, bw):
    req = urllib2.Request(url, bw)
    res_data = urllib2.urlopen(req)
    res = res_data.read()
    print(res)  # 打出响应信息


if __name__ == "__main__":
    url = "http://20.0.1.157:30043/OMP"
    bw = '请求报文'
    httpsend(url, bw)

##python3 不需要引入包,直接使用
from urllib import request
import json


# http发送报文
def httpsend(url, bw):
    textmod = json.dumps(bw).encode(encoding='utf-8')
    header_dict = {'Accept': 'application/json', 'Content-Type': 'application/json'}
    req = request.Request(url=url, data=textmod, headers=header_dict)
    res = request.urlopen(req)
    res = res.read()  # 默认获取到的是16进制'bytes'类型数据 Unicode编码
    res = res.decode(encoding='utf-8')  # 如果如需可读输出则需decode解码成对应编码
    print(res)  # 打出响应信息


if __name__ == "__main__":
    url = "http://test/encrypt/aes/multiple"
    bw = '1111,222'
    httpsend(url, bw)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值