从 Imgur API 上传图片给出了 400 个错误请求
Uploading images from Imgur API gives 400 bad request
我查了 Imgur 的 API,它说它在上传图片时接受二进制文件,我有这样的代码:
private async Task Upload()
{
var openfiledialog = new OpenFileDialog();
openfiledialog.Filter = "Image files (*.png) | *.png";
if (openfiledialog.ShowDialog() == DialogResult.OK)
{
using (var stream = openfiledialog.OpenFile())
{
byte[] imageBytes = new byte[stream.Length];
stream.Read(imageBytes, 0, imageBytes.Length);
var httpclient = new HttpClient();
httpclient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Client-ID", "MYCLIENTID");
httpclient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/octet-stream");
var status = await httpclient.PostAsync("https://api.imgur.com/3/upload", new ByteArrayContent(imageBytes));
}
}
}
但是,它给了我一个 400 错误的请求,我不确定我做错了什么。
Response body
我设法通过将图像转换为 base64 并使用 text/plain 内容类型 header.
来修复它
public async Task<string> UploadImage(string base64Image)
{
var httpclient = new HttpClient();
httpclient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Client-ID", "MYCLIENTID");
httpclient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "text/plain");
var response = await httpclient.PostAsync("https://api.imgur.com/3/Image", new StringContent(base64Image));
var stringcontent = await response.Content.ReadAsStringAsync();
var ImgurResponseModel = JsonConvert.DeserializeObject<ImgurResponseModel>(stringcontent);
return ImgurResponseModel.Data.Link;
}
我查了 Imgur 的 API,它说它在上传图片时接受二进制文件,我有这样的代码:
private async Task Upload()
{
var openfiledialog = new OpenFileDialog();
openfiledialog.Filter = "Image files (*.png) | *.png";
if (openfiledialog.ShowDialog() == DialogResult.OK)
{
using (var stream = openfiledialog.OpenFile())
{
byte[] imageBytes = new byte[stream.Length];
stream.Read(imageBytes, 0, imageBytes.Length);
var httpclient = new HttpClient();
httpclient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Client-ID", "MYCLIENTID");
httpclient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/octet-stream");
var status = await httpclient.PostAsync("https://api.imgur.com/3/upload", new ByteArrayContent(imageBytes));
}
}
}
但是,它给了我一个 400 错误的请求,我不确定我做错了什么。
Response body
我设法通过将图像转换为 base64 并使用 text/plain 内容类型 header.
来修复它 public async Task<string> UploadImage(string base64Image)
{
var httpclient = new HttpClient();
httpclient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Client-ID", "MYCLIENTID");
httpclient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "text/plain");
var response = await httpclient.PostAsync("https://api.imgur.com/3/Image", new StringContent(base64Image));
var stringcontent = await response.Content.ReadAsStringAsync();
var ImgurResponseModel = JsonConvert.DeserializeObject<ImgurResponseModel>(stringcontent);
return ImgurResponseModel.Data.Link;
}