如何在请求后发送Cookie [英] how to send cookies inside post request

查看:147
本文介绍了如何在请求后发送Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试从获取请求中发送带有PC上Cookie的发布请求

trying to send Post request with the cookies on my pc from get request

#! /usr/bin/python
import re #regex
import urllib
import urllib2
#get request 
x = urllib2.urlopen("http://www.example.com) #GET Request
cookies=x.headers['set-cookie'] #to get the cookies from get request 

url = 'http://example' # to know the values type any password to know the cookies 
values = {"username" : "admin",
          "passwd" : password,
          "lang" : "" ,
          "option" : "com_login",
          "task" : "login",
          "return" : "aW5kZXgucGhw" }

data = urllib.urlencode(values)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
result = response.read() 
cookies=response.headers['set-cookie'] #to get the last cookies from post req in this variable

然后我在Google中搜索

then i searched in google

如何在相同的帖子请求和发现内发送cookie

how to send cookies inside same post request and found

opener = urllib2.build_opener() # send the cookies
opener.addheaders.append(('Cookie', cookies)) # send the cookies
f = opener.open("http://example")

但是我不应该在我的代码中准确键入它

but i don't exactly where should i type it in my code

我需要做的就是

发送GET请求,将请求中的cookie放入变量中,然后使用我从GET请求中获得的值进行发布请求

send GET request, put the cookies from the request in variable,then make post request with the value that i got from the GET request

如果有人知道答案,我需要对我的代码进行编辑

if anyone know answer i need edit on my code

推荐答案

只需创建一个HTTP打开程序和cookiejar处理程序.因此,将检索cookie,并将它们自动一起传递给下一个请求.参见:

Just create a HTTP opener and a cookiejar handler. So cookies will be retrieved and will be passed together to next request automatically. See:

import urllib2 as net
import cookielib
import urllib   

cookiejar = cookielib.CookieJar()
cookiejar.clear_session_cookies()
opener = net.build_opener(net.HTTPCookieProcessor(cookiejar))

data = urllib.urlencode(values)
request  = net.Request(url, urllib.urlencode(data))
response = opener.open(request)

由于opener是全局处理程序,因此只需发出任何请求,从前一个请求发送的前一个cookie就会自动进入下一个请求(POST/GET).

As opener is a global handler, just make any request and the previous cookies sent from previous request will be in the next request (POST/GET), automatically.

这篇关于如何在请求后发送Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆