Linux命令发送Http的get或post请求(curl和wget两种方法)

Http请求指的是客户端向服务器的请求消息,Http请求主要分为get或post两种,在Linux系统下可以用curl和wget命令来模拟Http的请求。下面就来介绍一下Linux系统如何模拟Http的get或post请求。

一、get请求

1、使用curl命令:

curl “http://www.baidu.com” 如果这里的URL指向的是一个文件或者一幅图都可以直接下载到本地

curl -i “http://www.baidu.com” 显示全部信息

curl -l “http://www.baidu.com” 只显示头部信息

curl -v “http://www.baidu.com” 显示get请求全过程解析

2、使用wget命令:

wget “http://www.baidu.com”也可以

二、post请求

1、使用curl命令(通过-d参数,把访问参数放在里面):

curl -d “param1=value1¶m2=value2” “http://www.baidu.com”

  
2、使用wget命令:(–post-data参数来实现)

wget --post-data ‘user=foo&password=bar’ http://www.baidu.com

  
以上就是Linux模拟Http的get或post请求的方法了,这样一来Linux系统也能向远程服务器发送消息了。

示例:wget --post-data="" http://mcs-inner.99bill.com/mcs-gateway/mcs/task/clear

三、curl (可直接发送格式化请求例如json)

示例:目标url:http://fsc-inner.99bill.com/acs/deposit/{srcRef}

命令:curl -H "Content-type: application/json" -X POST -d '{"srcRef":"1002"}'http://fsc-inner.99bill.com/acs/deposit/1002

python的BaseHTTPServer模块接收post请求

#!/usr/bin/python
#encoding=utf-8
'''
基于BaseHTTPServer的http server实现,包括get,post方法,get参数接收,post参数接收。
'''
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import io,shutil  
import urllib
import os, sys

class MyRequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        mpath,margs=urllib.splitquery(self.path) # ?分割
        self.do_action(mpath, margs)

    def do_POST(self):
        mpath,margs=urllib.splitquery(self.path)
        datas = self.rfile.read(int(self.headers['content-length']))
        self.do_action(mpath, datas)

    def do_action(self, path, args):
            self.outputtxt(path + args )

    def outputtxt(self, content):
        #指定返回编码
        enc = "UTF-8"
        content = content.encode(enc)          
        f = io.BytesIO()
        f.write(content)
        f.seek(0)  
        self.send_response(200)  
        self.send_header("Content-type", "text/html; charset=%s" % enc)  
        self.send_header("Content-Length", str(len(content)))  
        self.end_headers()  
        shutil.copyfileobj(f,self.wfile)