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中import与from方法总结(推荐)

    python中import与from方法总结(推荐)

    这篇文章主要介绍了python中import与from方法总结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-03-03
  • 一文掌握python中的__init__的意思及使用场景分析

    一文掌握python中的__init__的意思及使用场景分析

    __init__是构造方法,谁调用,表示谁(更直观的理解就是类的方法中,谁调用,表示谁,见下面第一个代码)!!并不是必选项,也就是说在类中,这个不是必须用的,那什么场景需要用到,什么场景不需要用到呢,感兴趣的朋友跟随小编一起看看吧
    2023-02-02
  • python流程图和思维导图实例代码

    python流程图和思维导图实例代码

    这篇文章主要给大家介绍了关于python流程图和思维导图的相关资料,学习python过程中,画流程图可以有效的帮助你梳理程序的逻辑,本文通过示例代码介绍的非常详细,需要的朋友可以参考下
    2021-08-08
  • Python人工智能之路 之PyAudio 实现录音 自动化交互实现问答

    Python人工智能之路 之PyAudio 实现录音 自动化交互实现问答

    关于音频, PyAudio 这个库, 可以实现开启麦克风录音, 可以播放音频文件等等。文章介绍了如何使用Python第三方库PyAudio进行麦克风录音然后自动播放已经合成的语音实现语音交互回答,需要的朋友可以参考下
    2019-08-08
  • 基于Python编写一个PDF转换工具箱

    基于Python编写一个PDF转换工具箱

    这篇文章主要为大家详细介绍了如何使用Python编写一个PDF转换工具箱,可以实现PDF转图片,word,拆分,删除,提取等功能,感兴趣的可以了解下
    2024-12-12
  • Python中列表的常用操作详解

    Python中列表的常用操作详解

    这篇文章主要为大家详细介绍了python字典的常用操作方法,主要内容包含Python中列表(List)的详解操作方法,包含创建、访问、更新、删除、其它操作等,需要的朋友可以参考下
    2021-09-09
  • Python 内置模块 argparse快速入门教程

    Python 内置模块 argparse快速入门教程

    argparse模块是Python内置的用于命令项选项与参数解析的模块,argparse模块可以让人轻松编写用户友好的命令行接口,能够帮助程序员为模型定义参数,这篇文章主要介绍了快速入门Python内置模块argparse,需要的朋友可以参考下
    2023-06-06
  • Python实现数据库并行读取和写入实例

    Python实现数据库并行读取和写入实例

    本篇文章主要介绍了Python实现数据库并行读取和写入实例,非常具有实用价值,需要的朋友可以参考下
    2017-06-06
  • TensorFlow实现checkpoint文件转换为pb文件

    TensorFlow实现checkpoint文件转换为pb文件

    今天小编就为大家分享一篇TensorFlow实现checkpoint文件转换为pb文件,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-02-02
  • Django模板过滤器和继承示例详解

    Django模板过滤器和继承示例详解

    初入python和django做项目,遇到很多前端页面代码冗余的情况,特别是头部和脚部,代码都是一样的,所以下面这篇文章主要给大家介绍了关于Django模板过滤器和继承的相关资料,需要的朋友可以参考下
    2021-11-11

最新评论