【问题标题】:How do I upload document by converting HttpClient request to RestSharp request?如何通过将 HttpClient 请求转换为 RestSharp 请求来上传文档?
【发布时间】: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


【解决方案1】:

我刚刚解决了这个问题。

using (WebClient wc = new WebClient())
{
    byte[] value = wc.DownloadData("http://www.africau.edu/images/default/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", value, ParameterType.RequestBody)
        );
}

如你所见,我使用 WebClient.DownloadData() 而不是 StreamReader.BaseStream()

或者,您可以使用 File.ReadAllBytes()

将本地数据转换为 byte 数组
string entitySource = @"C:\Users\fcomak\Downloads\sample2.pdf";
byte[] value = File.ReadAllBytes(entitySource);
restClient.Execute(new RestRequest(entityBasePath + entityName + "/" + inventoryID + "/files/" + fileName, Method.PUT)
        .AddHeader("Content-Type", "application/pdf")
        .AddParameter("application/pdf", value, ParameterType.RequestBody)
        );

仅供参考

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-26
    • 2019-06-28
    • 2020-04-02
    • 1970-01-01
    相关资源
    最近更新 更多