[英]Receiving JSON data back from HTTP request
我有一個正常工作的 web 請求,但它只是返回狀態正常,但我需要 object 我要求它返回。 我不確定如何獲得我要求的 json 值。 我是使用 object HttpClient 的新手,是否有我遺漏的屬性? 我真的需要返回的 object。 謝謝你的幫助
撥打電話 - 運行良好會返回 OK 狀態。
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var responseMsg = client.GetAsync(string.Format("http://localhost:5057/api/Photo")).Result;
api 獲取方法
//Cut out alot of code but you get the idea
public string Get()
{
return JsonConvert.SerializeObject(returnedPhoto);
}
如果您指的是 .NET 4.5 中的 System.Net.HttpClient,則可以使用HttpResponseMessage.Content屬性作為HttpContent派生對象獲取 GetAsync 返回的內容。 然后,您可以使用HttpContent.ReadAsStringAsync方法將內容讀取為字符串,或使用ReadAsStreamAsync方法將內容讀取為流。
HttpClient類文檔包括以下示例:
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
基於@Panagiotis Kanavos的回答,這里有一個工作方法作為示例,它也將響應作為對象而不是字符串返回:
using System.Text;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json; // Nuget Package
public static async Task<object> PostCallAPI(string url, object jsonObject)
{
try
{
using (HttpClient client = new HttpClient())
{
var content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json");
var response = await client.PostAsync(url, content);
if (response != null)
{
var jsonString = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<object>(jsonString);
}
}
}
catch (Exception ex)
{
myCustomLogger.LogException(ex);
}
return null;
}
請記住,這只是一個示例,您可能希望將HttpClient
用作共享實例,而不是在 using 子句中使用它。
從 Microsoft System.Net.Http.Json
安裝這個 nuget 包。 它包含擴展方法。
然后using System.Net.Http.Json
添加
現在,您將能夠看到這些方法:
所以你現在可以這樣做:
await httpClient.GetFromJsonAsync<IList<WeatherForecast>>("weatherforecast");
來源: https : //www.stevejgordon.co.uk/sending-and-receiving-json-using-httpclient-with-system-net-http-json
我認為最短的方法是:
var client = new HttpClient();
string reqUrl = $"http://myhost.mydomain.com/api/products/{ProdId}";
var prodResp = await client.GetAsync(reqUrl);
if (!prodResp.IsSuccessStatusCode){
FailRequirement();
}
var prods = await prodResp.Content.ReadAsAsync<Products>();
通過以下方式對我來說效果很好 -
public async Task<object> TestMethod(TestModel model)
{
try
{
var apicallObject = new
{
Id= model.Id,
name= model.Name
};
if (apicallObject != null)
{
var bodyContent = JsonConvert.SerializeObject(apicallObject);
using (HttpClient client = new HttpClient())
{
var content = new StringContent(bodyContent.ToString(), Encoding.UTF8, "application/json");
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
client.DefaultRequestHeaders.Add("access-token", _token); // _token = access token
var response = await client.PostAsync(_url, content); // _url =api endpoint url
if (response != null)
{
var jsonString = await response.Content.ReadAsStringAsync();
try
{
var result = JsonConvert.DeserializeObject<TestModel2>(jsonString); // TestModel2 = deserialize object
}
catch (Exception e){
//msg
throw e;
}
}
}
}
}
catch (Exception ex)
{
throw ex;
}
return null;
}
我通常會做什么,類似於回答一:
var response = await httpClient.GetAsync(completeURL); // http://192.168.0.1:915/api/Controller/Object
if (response.IsSuccessStatusCode == true)
{
string res = await response.Content.ReadAsStringAsync();
var content = Json.Deserialize<Model>(res);
// do whatever you need with the JSON which is in 'content'
// ex: int id = content.Id;
Navigate();
return true;
}
else
{
await JSRuntime.Current.InvokeAsync<string>("alert", "Warning, the credentials you have entered are incorrect.");
return false;
}
其中“模型”是您的 C# 模型類。
下面的代碼用於訪問您的 HttpResponseMessage 並從 HttpContent 中提取您的響應。
string result = ret.Result.Content.ReadAsStringAsync().Result;
根據您的業務將您的 json 轉換為結構在我的情況下,BatchPDF 是一個復雜的 object,它由結果變量填充。
BatchPDF batchJson = JsonConvert.DeserializeObject<BatchPDF>(result);
return batchJson;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.