目录[-]

1、Python 发起http请求

#!/usr/bin/env python
#coding=utf-8
# license removed for ******
import rospy
import pycurl
import StringIO
import urllib
from std_msgs.msg import String
import json
import hashlib
from cyber_msgs.msg import Login

#----------------------------------定义测试变量---------------------------------#

jsonData = '{"msg":"OK"}'

#---------------------------------post函数封装----------------------------------#

def PostData(curl, url, data):
  local_iccid = global_parames_iccid + global_parames_iccid[0:12]
  head = 'token:'+ hash_sha256(local_iccid),
  buf = StringIO.StringIO()
  curl.setopt(pycurl.WRITEFUNCTION, buf.write)
  curl.setopt(pycurl.POSTFIELDS, data)
  curl.setopt(pycurl.URL, url)
  curl.setopt(pycurl.HTTPHEADER, head)
  print(url)
  #curl.setopt(pycurl.HEADERFUNCTION, getheader) #将返回的HTTP HEADER定向到回调函数getheader
  curl.setopt(pycurl.WRITEFUNCTION, getbody) #将返回的内容定向到回调函数getbody
  #curl.setopt(pycurl.WRITEHEADER, fileobj) #将返回的HTTP HEADER定向到fileobj文件对象
  #curl.setopt(pycurl.WRITEDATA, fileobj) #将返回的HTML内容定向到fileobj文件对象
  #curl.getinfo(pycurl.HTTP_CODE) #返回的HTTP状态码
  curl.perform()
  the_page = buf.getvalue()
  #print the_page
  buf.close()
  return the_page

def getbody(buf):
  print("Recived Data:")
  print(buf)

#--------------------------------自动处理cookile的函数--------------------------------#
  
def initCurl():
  c = pycurl.Curl()
  c.setopt(pycurl.COOKIEFILE, "cookie_file_name")#把cookie保存在该文件中
  c.setopt(pycurl.COOKIEJAR, "cookie_file_name")
  c.setopt(c.POST, 1) #1表示调用post方法而不是get
  c.setopt(pycurl.FOLLOWLOCATION, 1) #允许跟踪来源
  c.setopt(pycurl.MAXREDIRS, 5)
  #设置代理 如果有需要请去掉注释,并设置合适的参数
  #c.setopt(pycurl.PROXY, ‘http://11.11.11.11:8080′)
  #c.setopt(pycurl.PROXYUSERPWD, ‘aaa:aaa’)
  return c

#-----------------------------------get函数-----------------------------------#

def GetDate(curl, url):
  head = ['Accept:*/*','User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0']
  buf = StringIO.StringIO()
  curl.setopt(pycurl.WRITEFUNCTION, buf.write)
  curl.setopt(pycurl.URL, url)
  curl.setopt(pycurl.HTTPHEADER, head)
  curl.perform()
  the_page =buf.getvalue()
  buf.close()
  return the_page

if __name__ == "__main__":
  c = initCurl()
  try:
    get_parames()
    PostData(c, global_parames_url, "")
    #print html
    #text = json.loads(jsonData)
    #print(text["total"])
    get_mqtt_login_data()
  except rospy.ROSInternalException:
    print("Init Ros error")