[英]5 .NET HTTP libraries - where does Microsoft.Net.Http fit in?
[英]How to upload data with Microsoft.Net.Http?
過去,我制作了一個在endpoint
上縮減請求的類。 現在,我創建一個包含此方法的dll
,這是我要在此庫上轉換的代碼:
using (var client = new HttpClient())
{
string requestJson = JsonConvert.SerializeObject(data);
client.DefaultRequestHeaders.Add("token", token);
byte[] responseArray = client. 'there is no upload data method
// the bottom code is of the old method
byte[] responseArray = client.UploadData(requestURI, method, Encoding.UTF8.GetBytes(requestJson));
return Encoding.ASCII.GetString(responseArray);
}
在非便攜式庫System.Net
我可以調用client.UploadData
,但是在這里我只能看到:postAsync和putAsync,有一種方法獨立於put
或post
請求,使我可以將數據從client
發送到server
? 提前致謝。
在HTTP請求中,PUT和POST是將數據傳輸到服務器的正確方法,而獨立於這些方法發送數據是沒有意義的。 當您使用諸如System.Net中可用的客戶端時,這僅僅是從您身上抽象出來的。
在您的舊代碼中,您使用了一些傳入method
參數的方法來通過UploadData
方法發送數據,它可能是POST
或PUT
。 如果未為UploadData
指定方法,則使用POST
。 所以,你應該用PostAsync
或PutAsync
,根據您當前的代碼和值method
參數傳遞給UploadData
。
最簡單的方法是使用如下所示的內容:
using(var client = new HttpClient())
{
var response = await client.PostAsJsonAsync(requestUrl, data);
return await response.Content.ReadAsStringAsync();
}
PUT的代碼將相同,但使用PutAsJsonAsync
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.