【发布时间】:2020-11-28 01:32:35
【问题描述】:
登录到我使用的 API 后,我正在尝试使用 RestSharp 上传文档。
我可以使用 Postman 做到这一点。截图如下:
Postman 代码生成器为我生成此代码块:
var client = new RestClient("http://80.211.238.187/AcumaticaERP/entity/Default/17.200.001/StockItem/POSTMAN123/files/sample.pdf");
client.Timeout = -1;
var request = new RestRequest(Method.PUT);
request.AddHeader("Content-Type", "application/pdf");
request.AddParameter("application/pdf", "<file contents here>", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
但是我知道如何从上面的给定代码块编辑 file contents here> 部分。
我还能够使用相应 API 文档指南中建议的 HttpClient 来实现它:
using (StreamReader sr = new StreamReader(@"C:\Users\fcomak\Downloads\sample.pdf"))
{
_httpClient.PutAsync("http://80.211.238.187/AcumaticaERP/entity/Default/17.200.001/StockItem/POSTMAN123/files/sample.pdf", new StreamContent(sr.BaseStream))
.Result
.EnsureSuccessStatusCode();
}
但我需要将 HttpClient 请求转换为 RestSharp 请求。我尝试使用 RestSharp 来实现这一点,但失败了。即使我可以发送文件,其内容也无法正确浏览。这是我尝试过的代码块:
using (StreamReader sr = new StreamReader(@"C:\Users\fcomak\Downloads\sample.pdf"))
{
restClient.Execute(new RestRequest("http://80.211.238.187/AcumaticaERP/entity/Default/17.200.001/StockItem/POSTMAN123/files/sample.pdf", Method.PUT)
.AddHeader("Content-Type", "application/pdf")
.AddParameter("application/pdf", new StreamContent(sr.BaseStream), ParameterType.RequestBody));
}
顺便说一句,我可以通过使用这个 api 和这个 restClient 来发送或获取 json 内容。当然我已经登录了。我失败的原因是关于我的restClient。 如果有任何帮助,我将不胜感激。
【问题讨论】:
-
大概是
new StreamContent(sr.BaseStream)部分。 -
当我用记事本打开restClient上传的pdf文件时,它给了我这个文本:
System.Net.Http.StreamContent
标签: c# postman httpclient dotnet-httpclient restsharp