php 、go 、python http请求(get和post)

php get、post体验

php的get请求通过file_get_contents  直接请求

以下是post表单提交

function curl_post($url,  $params = array(), $timeout = 8)
    {
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL, $url);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        $data = curl_exec($ch);//运行curl
        curl_close($ch);
        return ($data);//输出结果
    }

以下是直接提交json数据提交

function curl_post_json($url, $params, $timeout = 8)
    {
        $headers = array(
            "Content-type: application/json;charset='utf-8'",
            "Accept: application/json",
            "Cache-Control: no-cache",
            "Pragma: no-cache",
        );
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60); //设置超时
        if(0 === strpos(strtolower($url), 'https')) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); //对认证证书来源的检查
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); //从证书中检查SSL加密算法是否存在
        }
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $data = curl_exec($ch);//CURLOPT_RETURNTRANSFER 不设置  curl_exec返回TRUE 设置  curl_exec返回json(此处) 失败都返回FALSE
        curl_close($ch);
        return ($data);//输出结果
    }

 

python2.6 和 python3 get、post 体验

总体感觉3对中文支持比较明显,但是post里面有坑,一般的post都还行,强烈建议后期开发用python2.6,相对成熟

python3 

# coding:utf-8


from urllib import request
from urllib import parse

def get():
    url = "http://120.26.39.165:28006/api/v1/park-num"
    req = request.Request(url)  # GET方法
    page = request.urlopen(req).read()
    page = page.decode('utf-8')
    return page


def post():
    sdata = '{"all":9582,"overground_cars":{"parkUuid":"","floorUuid":"","parkName":"\u82cf\u5dde\u5965\u4f53\u4e2d\u5fc3","floorName":"\u5730\u4e0a","leftNum":6615},"floor_car":[{"parkUuid":"cab11551985b4c73959649adda514b0d","parkName":"\u82cf\u5dde\u5965\u4f53\u4e2d\u5fc3","floorUuid":"847cc63e5d114c9982d51684b6eb9d1e","floorName":"2\u53f7\u8f66\u5e93","leftNum":514},{"parkUuid":"cab11551985b4c73959649adda514b0d","parkName":"\u82cf\u5dde\u5965\u4f53\u4e2d\u5fc3","floorUuid":"9dc655eaca6047f8a3aca399de503445","floorName":"B1","leftNum":910},{"parkUuid":"cab11551985b4c73959649adda514b0d","parkName":"\u82cf\u5dde\u5965\u4f53\u4e2d\u5fc3","floorUuid":"1b3b52fdef3843f1b4f8b9fd61285ff9","floorName":"B2","leftNum":187}]}';


    url = "http://120.26.39.165:28006/api/v1/insert_num"
    headers = {
        'User-Agent': r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
                      r'Chrome/45.0.2454.85 Safari/537.36 115Browser/6.0.3',
        'Referer': r'http://www.lagou.com/zhaopin/Python/?labelWords=label',
        'Connection': 'keep-alive'
    }

    data = {
        'cont': sdata
    }
    data = parse.urlencode()
    data = parse.urlencode(data).encode('utf-8')
    req = request.Request(url, headers=headers, data=data)
    page = request.urlopen(req).read()
    page = page.decode('utf-8')
    return page

s = post()
print(s)

 

python2.6

# !/usr/bin/python
# coding=utf-8

import hashlib
import json
import requests
import time
import datetime


class PostServices:
    """一个简单的类实例"""
    host = "http://192.168.143.251:81"
    appkey = "cf85e34a"
    secret = "d0927c5416a94c189cd34933be94c256"

    def __init__(self):
        pass

    def Get(self, url):
        """
        self.Get(url,data)
        :param url:
        :param data:
        :return:
        """
        req = requests.get(url)  # GET方法
        return req.text

    def Post(self, url, data):
        """
        self.Post(url,data)
        :param url:
        :param data:
        :return:
        """
        headers = {
            'X-AjaxPro-Method': 'ShowList',
            'Content-Type': 'application/json; charset=utf-8',
            'Content-Length': str(len(data))
        }

        # data = parse.urlencode(data).encode('utf-8')
        # data1 = json.loads(data)
        # data = urllib.parse.urlencode(data1).encode(encoding='UTF8')
        req = requests.post(url=url, data=data, headers=headers, timeout=20)
        # page = request.urlopen(req).read()
        # page = page.decode('utf-8')
        return req.text

 

go语言的get、post请求

get请求

package main

import (
"net/http"
"io/ioutil"
"fmt"
"github.com/go-irain/logger"
"strings"
"net"
"time"
"os"
"io"
)

func get() {
res, err := http.Get("https://www.hao123.com")
if err!= nil{
panic(err)
}
getRes , err := ioutil.ReadAll(res.Body)
if err!= nil{
panic(err)
}
fmt.Println(string(getRes))
}

func post() {
url := "http://cmb.com"
param := "name=aa"
/* 生成client,参数默认;
* 这个结构体有四个属性
* Transport(RoundTrepper);指定执行的独立、单次http请求的机制
* CheckRedirect(func(req *Request, via []*Request)err):指定处理重定向的策略,如果不为nil,客户端在执行重定向之前调用本函数字段.如果CheckRedirect 返回一个错误,本类型中的get方法不会发送请求,如果CheckRedirect为nil,就会采用默认策略:连续请求10次后停止;
* jar(CookieJar):jar指定cookie管理器,若果为nil请求中不会发送cookie,回复中的cookie会被忽略
* TimeOut(time.Duration):指定本类型请求的时间限制,为0表示不设置超时
*/
//client := &http.Client{} 这里初始化了一个默认的client,并没有配置一些请求的设置

//可以通过client中transport的Dail函数,在自定义Dail函数里面设置建立连接超时时长和发送接受数据超时
client := &http.Client{
Transport: &http.Transport{
Dial: func(netw, addr string) (net.Conn, error) {
conn, err := net.DialTimeout(netw, addr, time.Second*2) //设置建立连接超时
if err != nil {
return nil, err
}
conn.SetDeadline(time.Now().Add(time.Second * 2)) //设置发送接受数据超时
return conn, nil
},
ResponseHeaderTimeout: time.Second * 2,
},
}
reqest,err := http.NewRequest("POST",url,strings.NewReader(param)) //提交请求;用指定的方法,网址,可选的主体放回一个新的*Request
reqest.Header.Set("Content-Type","application/x-www-form-urlencoded")
if err != nil {
panic(err)
return
}
response,err := client.Do(reqest) //前面预处理一些参数,状态,Do执行发送;处理返回结果;Do:发送请求,
defer response.Body.Close()
stdout := os.Stdout //将结果定位到标准输出,也可以直接打印出来,或定位到其他地方进行相应处理
_,err = io.Copy(stdout,response.Body) //将第二个参数拷贝到第一个参数,直到第二参数到达EOF或发生错误,返回拷贝的字节喝遇到的第一个错误.
status := response.StatusCode //获取返回状态码,正常是200
body,err := ioutil.ReadAll(response.Body)
logger.Info(string(body))
logger.Info(status)
}

func main() {
post()
}

 更多go的http请求方法请参考,最好自己实践

转载于:https://www.cnblogs.com/akidongzi/p/9638861.html

你可能感兴趣的:(python,php,json)