簡體   English   中英

如何通過將 HttpClient 請求轉換為 RestSharp 請求來上傳文檔?

[英]How do I upload document by converting HttpClient request to RestSharp request?

在我登錄到我使用的 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);

但是 idk 如何編輯上面給定代碼塊中的 < file contents > 部分。

我還能夠使用相應 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。 如果有任何幫助,我將不勝感激。

我剛剛解決了這個問題。

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()將本地數據轉換為字節數組

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)
        );

供參考

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM