如何用 C# 编写 Python b“mystring”
本文关键字:mystring Python 何用 编写 | 更新日期: 2023-09-27 18:35:01
短篇小说:我试过了
Encoding.ASCII.GetBytes("mystring")
但它似乎不起作用...
说来话长:我正在尝试调用一个 API,并且我有这个 python 示例代码可用:
userpass = username + ":" + password
encoded_credentials = b"Basic " + base64.b64encode(userpass.encode('ascii'))
headers = {'Version': '2.0', 'Accept': 'application/json', 'Authorization': encoded_credentials}
url = 'https://' + server_ip + '/api/help/capabilities'
request = urllib.request.Request(url, headers=headers)
response = urllib.request.urlopen(request)
我制作的 c# 代码是:
string userpass = username + ":" + password;
byte[] encodedbytes = System.Text.ASCIIEncoding.ASCII.GetBytes(userpass);
var encoded_credentials = Encoding.ASCII.GetBytes("Basic ") + Convert.ToBase64String(encodedbytes);
var request = (HttpWebRequest)WebRequest.Create("https://" + server_ip + "/api/help/capabilities");
request.Method = "GET";
request.ContentType = "application/json";
request.Headers.Add("Authorization", encoded_credentials);
var response = (HttpWebResponse)request.GetResponse()
我得到的结果是 401,未经授权...所以我相信我在用户名密码的编码过程中错过了一些东西!
var encoded_credentials = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(userpass));
这就是我的"长话短说"问题的答案!调试 python 代码(确实授权(后,我设法弄清楚了,所以我拿了encoded_credentials并在我的 c# 代码中使用它,所以它也成功授权了......然后我将错误值与正确的值进行比较,经过几次尝试,我最终得到了正确的值!
这使我得出结论,"短篇小说"问题的正确答案只是:
"mystring"