作为(重新)熟悉 C# 的编程练习,我一直在将我的程序从 Python 移植到 C#。到目前为止一切顺利,但该程序的核心功能之一是获取构建的信息,将其传递给给定的 API,然后取回图像。据我从我找到的教程中可以看出,我已经编写了应该等效的代码,但到目前为止我收到了 400 个错误。
在 Python 中,我的解决方案如下所示:
import requests
#Simple program:
#Create a request to the API and return an image.
url = "https://givenurl.com/api/"
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
dataFile = open("Some Data.txt",'r')
metaFile = open("Some Metadata.txt",'r')
data = dataFile.read()
metadata = metaFile.read()
dataFile.close()
metaFile.close()
totaldata = {'data': data, 'metadata': metadata}
param1 = "foo"
param2 = "bar"
r = requests.post(url=url, data=totaldata , headers=headers, params={"param1": param1, "param2": param2})
print(r.status_code)
file = open("Some Data Picture.jpg", "wb")
file.write(r.content)
file.close()
等效的 C# 代码如下所示:
internal class ThisClass{
private static HttpClient client;
public ThisClass(){
client = new HttpClient();
}
public async void imageCreate(dataStruct data)
{
//Take a dataStruct data from elsewhere in the program, use the HTTPClient set up at the
//beginning of this class and write the file to data.filepath
string uri = "https://givenurl.com/api/";
var payload = new Dictionary<string,string>
{
{"data", data.data},
{"metadata", data.metadata},
{"param1", data.param1},
{"param2", data.param2}
};
var info = new FormUrlEncodedContent(payload);
var res = await client.PostAsync(uri, info);
System.Diagnostics.Debug.WriteLine("Response Code: " + res.StatusCode);
if (res.IsSuccessStatusCode) {
Image picture = Image.FromStream(await res.Content.ReadAsStreamAsync());
picture.Save(data.filename);
}
}
虽然 Python 脚本每次都有效,但我的 C# 实现每次都返回 400 错误。