python使用requests通过代理地址发送application/x-www-form-urlencoded报文数据

 通过代理地址发送以form表单数据格式(它要求数据名称(name)和数据值(value)之间以等号相连,与另一组name/value值之间用&相连。例如:parameter1=12345&parameter2=23456。)请求到远程服务器,并获取请求响应报文。建议沟通开发确认数据名称都有哪些。该请求消息头中"Content-Type":字段为"application/x-www-form-urlencoded; charset=UTF-8"。用户可以根据需要新增请求头字段,只需传入请求头中待新增的除了'Content-Type'字段外的其他字段数据。

    def client_post_formurlencodeddata_proxy_requests(self,request_url,requestdata,headerdict={},**kwargs):
        #功能说明:通过代理地址发送以form表单数据格式(它要求数据名称(name)和数据值(value)之间以等号相连,与另一组name/value值之间用&相连。例如:parameter1=12345&parameter2=23456。)请求到远程服务器,并获取请求响应报文。该请求消息头要求为:{"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"}。
        #输入参数说明:接收请求的URL;请求报文数据,格式为name1=value1&name2=value2、待添加到请求头中的字段值组成的字典,默认为{},表示不新增字段、http或者https请求代理地址组成的字典,格式例如为{'http': 'http://192.168.111.222:8888', 'https': 'http://192.168.333.444:8888'}。
        #输出参数:请求响应报文
        #by xiaocc[20180709]        

        #从构造的请求报文文件中获取请求报文数据
#         requestJSONdata=str(requestJSONdata).replace("+", "%2B")
        requestdata=requestdata.encode("utf-8")
        #默认请求头
        head = {"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", 'Connection': 'close'}
        print u'请求头待更新的数据:',headerdict,u'该数据类型为:',type(headerdict)
        #比对输入的header与默认的head,根据输入要求更新请求头
        if headerdict=='{}':#若未传入更新的请求头数据,则选择默认请求头
            pass
        elif type(headerdict) in (dict,): #若传入的更新的请求头数据为字典格式,则更新到默认请求头
            for key in headerdict: #判断待添加到默认head中的键值对
                head[key]=headerdict[key] #根据输入更新默认head数据
        else:
            logging.error(u'请确保输入的请求头更新数据格式为字典格式!' )
            raise Exception
        print u'服务器接收请求报文的地址为:: ',request_url
        print u'客户端请求报文为(客户端 --> 服务器):
',str(requestdata).decode('utf-8')

        proxyurl= kwargs['proxyurl']
        print u'请求代理地址为:',proxyurl        
        #发送请求报文到服务端
        r = requests.post(request_url,data=requestdata,headers=head,proxies=proxyurl,verify=False)
        print u'请求头headers为: ',r.request.headers
        
        #获取请求响应报文数据
        responsedata=r.text
        print u"get the status: ",r.status_code
        print u'服务器响应报文为(客户端  <-- 服务器):
 ',responsedata
  
        #返回请求响应报文
        return responsedata

  

原文地址:https://www.cnblogs.com/apple2016/p/14250308.html