简体   繁体   English

如何在Python请求库中设置参数

[英]How to set params in Python requests library

I have the following code using urllib in Python 2.7 and its working. 我在Python 2.7中使用urllib并使用以下代码。 I'm trying to do the same request using the requests library but I cant get it to work. 我正在尝试使用请求库执行相同的请求,但无法使其正常工作。

import urllib
import urllib2
import json

req = urllib2.Request(url='https://testone.limequery.com/index.php/admin/remotecontrol',\
                          data='{\"method\":\"get_session_key\",\"params\":[\"username\",\"password\"],\"id\":1}')
req.add_header('content-type', 'application/json')
req.add_header('connection', 'Keep-Alive')

f = urllib2.urlopen(req)
myretun = f.read()

j=json.loads(myretun)
print(j['result'])

Using requests library( Doesn't work) 使用请求库(不起作用)

import requests
import json

d= {"method":"get_session_key","params":["username","password"],"id":"1"}


headers = {'content-type' :'application/json','connection': 'Keep-Alive'}
req2 = requests.get(url='https://testone.limequery.com/index.php/admin/remotecontrol',data=d,headers=headers)

json_data = json.loads(req2.text)
print(json data['result']) 

I'm getting an error JSONDecodeError: Expecting value: line 1 column 1 (char 0) How can I make the code work with the requests library? 我收到错误JSONDecodeError: Expecting value: line 1 column 1 (char 0)如何使代码与请求库一起使用?

First, you're sending the wrong type of request. 首先,您发送的请求类型错误。 You're sending a GET request, but you need to send a POST, with requests.post . 你发送一个GET请求,但你需要发送一个POST,与requests.post

Second, passing a dict as data will form-encode the data rather than JSON-encoding it. 其次,将字典作为data传递将对data进行形式编码,而不是对JSON进行编码。 If you want to use JSON in your request body, use the json argument, not data : 如果要在请求正文中使用JSON,请使用json参数,而不要使用data

requests.post(url=..., json=d)

Reference Link: http://docs.python-requests.org/en/master/api/ 参考链接: http : //docs.python-requests.org/en/master/api/

You can use requests module of python like so 您可以像这样使用python的请求模块

import requests
Req = requests.request(
                        method     = "GET", # or "POST", "PUT", "DELETE", "PATCH" etcetera
                        url        = "http(s)://*", 
                        params     = {"key": "value"}, # IF GET Request  (Optional)
                        data       = {"key": "value"}, # IF POST Request (Optional)
                        headers    = {"header_name": "header_value"}    # (Optional)
)
print Req.content

You can surround the code with try::catch block like below to catch any exception thrown by requests module 您可以使用try :: catch块将代码括起来,如下所示,以捕获请求模块引发的任何异常

try:
    # requests.request(** Arguments)
except requests.exceptions.RequestException as e:
    print e

For full argument list, please check reference link. 有关完整的参数列表,请检查参考链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM