[英]Using C# HttpClient to POST File without multipart/form-data
I'm trying to interact with a API that doesn't support multipart/form-data for uploading a file.我正在尝试与不支持用于上传文件的 multipart/form-data 的 API 交互。
I've been able to get this to work with the older WebClient but since it's being deprecated I wanted to utilize the newer HttpClient.我已经能够让它与较旧的 WebClient 一起使用,但由于它已被弃用,我想使用较新的 HttpClient。
The code I have for WebClient that works with this end point looks like this:我为 WebClient 提供的与此端点一起使用的代码如下所示:
using (WebClient client = new WebClient())
{
byte[] file = File.ReadAllBytes(filePath);
client.Headers.Add("Authorization", apiKey);
client.Headers.Add("Content-Type", "application/pdf");
byte[] rawResponse = client.UploadData(uploadURI.ToString(), file);
string response = System.Text.Encoding.ASCII.GetString(rawResponse);
JsonDocument doc = JsonDocument.Parse(response);
return doc.RootElement.GetProperty("documentId").ToString();
}
I've not found a way to get an equivalent upload to work with HttpClient since it seems to always use multipart.我还没有找到一种方法来让等效的上传与 HttpClient 一起使用,因为它似乎总是使用多部分。
What speaks against using simply HttpClient's PostAsync method in conjunction with ByteArrayContent ?有什么反对将 HttpClient 的PostAsync方法与ByteArrayContent结合使用?
byte[] fileData = ...;
var payload = new ByteArrayContent(fileData);
payload.Headers.Add("Content-Type", "application/pdf");
myHttpClient.PostAsync(uploadURI, payload);
I think it would look something like this我认为它看起来像这样
using var client = new HttpClient();
var file = File.ReadAllBytes(filePath);
var content = new ByteArrayContent(file);
content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
var result = client.PostAsync(uploadURI.ToString(), content).Result;
result.EnsureSuccessStatusCode();
var response = await result.Content.ReadAsStringAsync();
var doc = JsonDocument.Parse(response);
return doc.RootElement.GetProperty("documentId").ToString();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.