首页 > 解决方案 > Python3 http.client 与 Requests 不起作用

问题描述

python3 中的相同代码是用 http.client 和 requests 编写的。它适用于 http.client,不适用于请求。

我在日志中看到的唯一区别是工作请求是 http/1.0,而不工作的是 http/1.1。

在代码示例下方。

import http.client
import mimetypes
from codecs import encode
import requests

username = ""
passwrord =""

conn = http.client.HTTPSConnection("wordpressdomain.com")
dataList = []
boundary = 'wL36Yn8afVp8Ag7AmP8qZ0SA4n1v9T'
boundary = ''
dataList.append(encode('--' + boundary))
dataList.append(encode('Content-Disposition: form-data; name=username;'))

dataList.append(encode('Content-Type: {}'.format('text/plain')))
dataList.append(encode(''))

dataList.append(encode(username))
dataList.append(encode('--' + boundary))
dataList.append(encode('Content-Disposition: form-data; name=password;'))

dataList.append(encode('Content-Type: {}'.format('text/plain')))
dataList.append(encode(''))

dataList.append(encode(password))
dataList.append(encode('--'+boundary+'--'))
dataList.append(encode(''))
body = b'\r\n'.join(dataList)
payload = body
headers = {
   'Content-type': 'multipart/form-data; boundary={}'.format(boundary) 
}
conn.request("POST", "/wp/wp-json/jwt-auth/v1/token", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))



url = "https://wordpressdomain.com/wp/wp-json/jwt-auth/v1/token"

payload={'username': username, password: password}

files=[

]
headers = headers

r = requests.request("POST", url, headers=headers, data=payload, files=files)
print (r.status_code)
print (r.headers['content-type'])
print (r.encoding)
print (r.text)

输出是

##Output from http.client##
{"success":true,"statusCode":200,"code":"jwt_auth_valid_credential","message":"Credential is valid","data":{"token":"TOKEN","id":2,"email":"email@email.com","nicename":"dev-api","firstName":"","lastName":"","displayName":"dev-api"}}


##Output from Requests##
403
text/html
ISO-8859-1
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx</center>
</body>
</html>

在服务器日志中我看到了这个 日志输出

与请求相同的代码也适用于我的本地开发环境,但是当我发布到服务器上的开发环境时它不起作用。

我会很感激你的帮助。

多谢

标签: python-3.xjwtwordpress-rest-api

解决方案


推荐阅读