how to send cookies inside post request

蓝咒 提交于 2019-12-13 04:31:56

问题


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

then i searched in google

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

what i need to do exactly is to

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


回答1:


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)

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.




回答2:


You should really look into the requests library python has to offer. All you need to do is make a dictionary for you cookies key/value pair and pass it is as an arg.

Your entire code could be replaced by

#import requests
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" }
session = requests.Session()
response = session.get(url, data=values)
cookies = session.cookies.get_dict()
response = reqeusts.post(url, data=values, cookies=cookies)

The second piece of code is probably what you want, but depends on the format of the response.



来源:https://stackoverflow.com/questions/31756661/how-to-send-cookies-inside-post-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!