python3 http.client 网络请求方式

 更新时间:2023年09月05日 11:10:45   作者:cocoajin  
这篇文章主要介绍了python3 http.client 网络请求方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

python3 http.client 网络请求

一、get 请求

'''
Created on 2014年4月21日
@author: dev.keke@gmail.com
'''
import http.client
#简单的GET请求
con = http.client.HTTPConnection('www.baidu.com')
con.request("GET", "/index.html",'',{})
resu = con.getresponse()
print(resu.status,resu.reason,resu.info())  #打印读取到的数据
#打印读取的数据
print (resu.read())
#测试一个无效的请求
inCon = http.client.HTTPConnection('www.baidu.com')
inCon.request('GET', 'None.html')
resu2 = inCon.getresponse()
print('\n')
print(resu2.status,resu2.msg)

二、POST 请求

import http.client,urllib.parse
pararms = urllib.parse.urlencode({'@number': 12524, '@type': 'issue', '@action': 'show'})
headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"}
conn = http.client.HTTPConnection("bugs.python.org")
conn.request('POST', '', pararms, headers)
response = conn.getresponse()
print(response.status, response.reason)
data = response.read()
print(data)
conn.close()

打印结果 :

302 Found
b'Redirecting to <a href="http://bugs.python.org/issue12524">http://bugs.python.org/issue12524</a>'

三、head 请求

>>> import http.client
>>> conn = http.client.HTTPConnection("www.python.org")
>>> conn.request("HEAD","/index.html")
>>> res = conn.getresponse()
>>> print(res.status, res.reason)
200 OK
>>> data = res.read()
>>> print(len(data))
0
>>> data == b''
True

四、put 请求

>>> # This creates an HTTP message
>>> # with the content of BODY as the enclosed representation
>>> # for the resource http://localhost:8080/file
...
>>> import http.client
>>> BODY = "***filecontents***"
>>> conn = http.client.HTTPConnection("localhost", 8080)
>>> conn.request("PUT", "/file", BODY)
>>> response = conn.getresponse()
>>> print(response.status, response.reason)
200, OK

参考:

https://docs.python.org/3.4/library/http.client.html?highlight=http.client#module-http.client

python3 http.client使用实例

使用实例

# -*- coding: utf-8 -*-
# @Time    : 2020/6/8 5:24 下午
# @Author  : renwoxing
# @File    : httpclient.py
# @Software: PyCharm
import http.client
if __name__ == '__main__':
    headers = {
        "Connection": "keep-alive",
    }
    conn = http.client.HTTPConnection('10.9.1.17:8000')
    for var in range(100):
        conn.request('GET', '/json_test', None, headers)
        res = conn.getresponse()
     print(res.status, res.code)
    conn.close()
    print("连接已经关闭")
#coding=utf-8
import http.client, urllib.parse
import http.client, urllib.parse
import random
USER_AGENTS = [
    "Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; fr) Presto/2.9.168 Version/11.52",
    'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'
]
def get_demo(num,keyword):
    page = urllib.parse.urlencode({'page':num})
    params = urllib.parse.urlencode({})
    headers = {'Referer': 'http://t66y.com/index.php',
               'User-Agent': random.choice(USER_AGENTS ),
               'Accept-Language': 'zh-CN,zh;q=0.9',
               }
    conn = http.client.HTTPConnection("t66y.com", timeout=10)
    conn.request("GET", "/thread0806.php?fid=22&"+page, params, headers)
    r1 = conn.getresponse()
    #print(r1.read())
    html = r1.read()
    data = html.decode('gbk')  # This will return entire content.
    content = data.find(keyword)
    if content != -1:
        print('bingo:'+page)
    else:
        print('try {},status:{}'.format(page, r1.status))
def post_demo():
    params = urllib.parse.urlencode({'qruuid': 'asdf', 'user_uuid': '3423412dfasf'})
    headers = {"Content-type": "application/x-www-form-urlencoded",
               "Accept": "application/json"}
    conn = http.client.HTTPSConnection("wx.coderr.cn")
    conn.request("POST", "/api/qrcode", params, headers)
    response = conn.getresponse()
    print(response.status, response.reason)
    if not response.closed:
        data = response.read()
        print(data, type(data.decode('utf-8')))
    conn.close()
if __name__ == '__main__':
	pass

参考范例:

https://www.journaldev.com/19213/python-http-client-request-get-post

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • Python利用缓存流实现压缩PDF文件

    Python利用缓存流实现压缩PDF文件

    在Python中,有许多库可以用来压缩PDF文件,其中最常用的是PyPDF2和PDFMiner,本文将为大家介绍一个新的方法,即使用缓存流压缩PDF文件,感兴趣的可以了解下
    2023-08-08
  • Python环境下安装使用异步任务队列包Celery的基础教程

    Python环境下安装使用异步任务队列包Celery的基础教程

    这篇文章主要介绍了Python环境下安装使用异步任务队列包Celery的基础教程,Celery的分布式任务管理适合用于服务器集群的管理和维护,需要的朋友可以参考下
    2016-05-05
  • 详解python和matlab的优势与区别

    详解python和matlab的优势与区别

    在本文中小编给大家分享的是关于python和matlab的优势与区别的知识点以及实例代码,需要的朋友们参考学习下。
    2019-06-06
  • PyTorch函数torch.cat与torch.stac的区别小结

    PyTorch函数torch.cat与torch.stac的区别小结

    Pytorch中常用的两个拼接函数torch.cat() 和 torch.stack(),本文主要介绍了这两个函数的用法加区别,具有一定的参考价值,感兴趣的可以了解一下
    2023-09-09
  • python 生成任意形状的凸包图代码

    python 生成任意形状的凸包图代码

    这篇文章主要介绍了python 生成任意形状的凸包图代码,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-04-04
  • Pandas筛选DataFrame含有空值的数据行的实现

    Pandas筛选DataFrame含有空值的数据行的实现

    本文主要介绍了Pandas筛选DataFrame含有空值的数据行的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-07-07
  • Python OpenCV机器学习之图像识别详解

    Python OpenCV机器学习之图像识别详解

    OpenCV中也提供了一些机器学习的方法,例如DNN等。本文将为大家详细介绍一下OpenCV中利用机器学习实现的一些图片识别功能:人脸识别、车牌识别等,感兴趣的可以了解一下
    2022-01-01
  • 哈工大自然语言处理工具箱之ltp在windows10下的安装使用教程

    哈工大自然语言处理工具箱之ltp在windows10下的安装使用教程

    这篇文章主要介绍了哈工大自然语言处理工具箱之ltp在windows10下的安装使用教程,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-05-05
  • python通用日志使用小结

    python通用日志使用小结

    日志则是程序中非常重要的一部分,它可以记录程序运行中的异常、警告等信息,方便开发人员调试程序,本文就来介绍一下python通用日志使用小结,感兴趣的可以了解一下
    2023-11-11
  • Python函数默认参数常见问题及解决方案

    Python函数默认参数常见问题及解决方案

    这篇文章主要介绍了Python函数默认参数常见问题及解决方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-03-03

最新评论