[英]HttpClient Post Call
我想使用 HttpClient 進行 REST POST 調用。我一直有錯誤 - 'RestCall.PostRestCall(string, string, string, string)':並非所有代碼路徑都返回一個值'
下面是我的代碼。 它的意思是接收 baseUrl、contentType、requestBody、httpMethod; 作為輸入參數並返回響應狀態碼、狀態描述和響應內容。
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace RestPostCall
{
public class RestCall
{
public static string PostRestCall(string baseURL, string httpMethod, string contentType, string requestBody)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(baseURL);
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue(contentType));
// List data response.
HttpResponseMessage response = client.GetAsync(requestBody).Result;
if (response.IsSuccessStatusCode)
{
// Parse the response body.
var dataObjects = response.Content.ReadAsAsync<IEnumerable<IDataObject>>().Result;
//Make sure to add a reference to System.Net.Http.Formatting.dll
}
else
{
Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
}
//Make any other calls using HttpClient here.
//Dispose once all HttpClient calls are complete.
client.Dispose();
}
}
}
您的方法不返回任何值,因此更改簽名以返回void
類型:
public static void PostRestCall(string baseURL, string httpMethod, string contentType,
string requestBody)
將您的方法返回類型更改為 void,或者如果您想返回任何值,請使用 return 語句。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.