use*_*883 63 c# httpwebrequest
我有一个正常工作的Web请求,但它只是返回状态OK,但我需要我要求它返回的对象.我不知道如何获取我要求的json值.我是新手使用对象HttpClient,有没有我错过的属性?我真的需要返回的对象.谢谢你的帮助
进行调用 - 运行正常返回状态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;
Run Code Online (Sandbox Code Playgroud)
api get方法
//Cut out alot of code but you get the idea
public string Get()
{
return JsonConvert.SerializeObject(returnedPhoto);
}
Run Code Online (Sandbox Code Playgroud)
Pan*_*vos 123
如果您在.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();
Run Code Online (Sandbox Code Playgroud)
ala*_*a27 22
从 Microsoft 安装这个 nuget 包System.Net.Http.Json。它包含扩展方法。
然后加 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
Wou*_*rck 19
基于@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;
}
Run Code Online (Sandbox Code Playgroud)
请记住,这只是一个示例,您可能希望将其HttpClient用作共享实例,而不是在using子句中使用它.
我认为最短的方法是:
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>();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
157644 次 |
| 最近记录: |