我想将以下 Http 请求的 Python 代码片段转换为等效的 Java 代码,
import requests
from requests.auth import HTTPBasicAuth
from numpy import array
try:
from commands import getoutput # python 2
except ImportError:
from subprocess import getoutput # python 3
SELDON_API_IP="35.192.98.23"
def get_token():
payload = {'grant_type': 'client_credentials'}
response = requests.post(
"http://{}:8080/oauth/token".format(SELDON_API_IP),
auth=HTTPBasicAuth('oauth-key', 'oauth-secret'),
data=payload)
token = response.json()["access_token"]
return token
def rest_request():
token = get_token()
headers = {'Authorization': 'Bearer '+token}
payload = {'meta':{},'data':{'ndarray':[[101]]}}
response = requests.post(
"http://{}:8080/api/v0.1/predictions".format(SELDON_API_IP),
headers=headers,
json=payload)
print(response.text)
rest_request()
我尝试使用 unirest Java 转换 get_token()
部分
HttpResponse<String> response = Unirest.post("http://35.192.98.23:8080/oauth/token")
.header("content-type", "application/json")
.body("{\"grant_type\":\"client_credentials\",\"username\": \"oauth-key\",\"password\": \"oauth-secret\"}")
.asString();
但在此 Java 代码中,我收到错误“需要完全身份验证”。如何将这个完整的 Python 代码片段转换为 Java 代码(有或没有 unirest,都可以)?
最佳答案
用户名和密码不应该是 JSON 正文的一部分。它不在 Python 代码中。用户名和密码是 auth
参数的一部分。它所做的是创建一个 Authorization
header 。基于此 HTTPBasicAuth
,似乎 Basic Authentication用来。这意味着 Authorization
header 的值应该是
"Basic base64(username:password)",其中
base64 是一个通用函数,它将以 64 为基数对字符串进行编码
“:”`,用户名和密码,用冒号分隔。
在 Java 8 中,您可以使用 Base64对值进行编码的类。所以你会做
String credentials = "ouath-key:oauth-secret";
String base64 = Base64.getEncoder().encodeAsString(credentials.getBytes(StandardCharsets.UTF_8));
HttpResponse<String> response = Unirest.post("http://35.192.98.23:8080/oauth/token")
.header("content-type", "application/json")
.header("Authorization", "Basic " + base64)
...
关于java - 将 Python Http 请求转换为 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49989063/