用python实现多种http请求 | LSABLOG

首页 » Program » Python » 正文

用python实现多种http请求

0x00 主要的HTTP请求:

1. GET :从指定的服务器中获取数据。
2. POST :提交数据给指定的服务器处理。
3. HEAD:类似于get请求,只不过返回的响应中没有具体的内容,用于获取报头。
4. OPTIONS:查询可以执行哪些请求,也可以利用向Web服务器发送’*’的请求来测试服务器的的性能。
5. PUT:向指定资源位置上传其最新内容。
6. MOVE:请求服务器将指定的页面移至另一个网络地址。
7. DELETE:请求服务器删除Request-URI所标识的资源。
8. TRACE:回显服务器收到的请求,主要用于测试或诊断。
9. CONNECT:HTTP/1.1协议中预留给能够将连接改为管道方式的代理服务器。
10. COPY:请求服务器将指定的页面拷贝至另一个网络地址。
11. LINK:请求服务器建立链接关系。
12. UNLINK:断开链接关系。
13. LOCK(wedav):加锁。
14. UNLOCK(wedav):解锁。

0x01 python实现get,post,put,delete,options,head 请求:

利用了urllib2,requests,httplib库,其实利用其中之一便可以实现。

get请求比较简单,直接利用urllib2。

post请求由于可能需要cookie,header,data等元素,而且要看具体场合,这里就用requests简单post一下。

put请求用urllib2,实现了两遍,一个用opener一个不用opener,区别不大,实现了put文件到服务器的功能。

delete请求也实现了两遍,一个用http的client一个用urllib2,实现了删除服务器文件的功能。

options请求用httplib实现,用来获取信息(主要是allow的请求)。

head请求用httplib实现,用来获取报头信息。

 

0x02 源码:

# -*- coding:utf-8 -*-
#Author:LSA
#Description:http's get,post,put,delete,option,head methods
#Date:20170804
#Version:v1.0

import urllib2
import urllib
import json
import httplib
import requests
import sys
from http import client

def http_get(url):
    rsp = urllib2.urlopen('http://'+url)
    return rsp.read()

def http_post(url):
    data = {'user':'lsa','pwd':'123456'}
    rsp = requests.post('http://'+url,data=data)
    return rsp.content

def http_put(url):
    opener = urllib2.build_opener(urllib2.HTTPHandler)  
    upfilepath = raw_input('upload file path: http://'+url+'/')
    localfilepath = raw_input('local file path: ')
    with open(localfilepath) as f:
        data = f.read()
    rqt = urllib2.Request('http://'+url+'/'+upfilepath,data=data)
    #rqt.add_header("Content-Type", "image/png")
    rqt.get_method = lambda:'PUT'
    #rsp = urllib2.urlopen(rqt)
    #return rsp.read()  
    rsp = opener.open(rqt)
    return rsp.read()

def http_put2(url):
      
    upfilepath = raw_input('upload file path: http://'+url+'/')
    localfilepath = raw_input('local file path: ')
    with open(localfilepath) as f:
        data = f.read()
    rqt = urllib2.Request('http://'+url+'/'+upfilepath,data=data)
    #rqt.add_header("Content-Type", "image/png")
    rqt.get_method = lambda:'PUT'
    rsp = urllib2.urlopen(rqt)
    return rsp.read()
    #rsp = opener.open(rqt)
    


def http_delete(url):
    header = {
            "Accept": "*/*",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-cn,zh;q=0.8",
            "Connection": "keep-alive",
        }
    

    #port = url.split(':')[1].split('/')[0]
    delfilepath = raw_input('target delete file path: '+url)
        conn = client.HTTPConnection(url)
        conn.request(method="DELETE", url='http://'+url+delfilepath, headers=header)
        rsp = conn.getresponse().read().decode("utf-8")
    #opener = urllib2.build_opener(urllib2.HTTPHandler)
    #data = {'':''}
    #dataToJson = json.dumps(data)
    #rqt = urllib2.Request('http://'+url+delfilepath)
    #rqt.get_method = lambda:'DELETE'
    #rsp = opener.open(rqt)
    return rsp
    
        


def http_delete2(url):
    delfilepath = raw_input('target delete file path: '+url)
    opener = urllib2.build_opener(urllib2.HTTPHandler)
    #data = {'':''}
    #dataToJson = json.dumps(data)
    rqt = urllib2.Request('http://'+url+delfilepath)
    rqt.get_method = lambda:'DELETE'
    rsp = opener.open(rqt)
    return rsp.read()


    
def http_options(url):
    if ':' in url:
        port = url.split(':')[1].split('/')[0]
        conn = httplib.HTTPConnection(url)
        conn.request("OPTIONS","/")
        rsp = conn.getresponse()
        return rsp.msg.dict
    else:
        conn = httplib.HTTPConnection(url,80)
        conn.request("OPTIONS","/")
        rsp = conn.getresponse()
        return rsp.msg.dict

def http_head(url):
    if ':' in url:
        conn = httplib.HTTPConnection(url)
        conn.request("HEAD","/")
        rsp = conn.getresponse()
        return rsp.msg
    else:       
        conn = httplib.HTTPConnection(url,80)
        conn.request("HEAD","/")
        rsp = conn.getresponse()
        return rsp.msg

switcher = {'get':http_get,
        'post':http_post,
            'put':http_put,
        'delete':http_delete,
        'options':http_options,
        'head':http_head,
        'delete2':http_delete2,
        'put2':http_put2,
    }

if __name__ == '__main__':
    url = raw_input('target url: ')
    httpMethod = raw_input('http method: ')
    method = switcher.get(httpMethod,lambda(argu):'Error method!')
    rsp = method(url)
    print rsp

 

0x03 部分运行效果:

put请求:                                                               delete请求:

     

options请求:                                                          head请求:

      

 

0x04 结语:

好久没写代码了,feeling下降了很多,这个v1.0版开发的初衷是为了熟悉下主要的http请求,可完善扩展的地方还有很多,有空再写v2.0版吧。

Comment