C# 从 HTTP 请求接收 JSON 数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10928528/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Receiving JSON data back from HTTP request
提问by user516883
I have a web request that is working properly, but it is just returning the status OK, but I need the object I am asking for it to return. I am not sure how to get the json value I am requesting. I am new to using the object HttpClient, is there a property I am missing out on? I really need the returning object. Thanks for any help
我有一个正常工作的 Web 请求,但它只是返回状态 OK,但我需要我要求它返回的对象。我不确定如何获取我请求的 json 值。我是使用对象 HttpClient 的新手,是否有我遗漏的属性?我真的需要返回的对象。谢谢你的帮助
Making the call - runs fine returns the status OK.
进行调用 - 运行良好返回状态 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;
The api get method
api获取方法
//Cut out alot of code but you get the idea
public string Get()
{
return JsonConvert.SerializeObject(returnedPhoto);
}
采纳答案by Panagiotis Kanavos
If you are referring to the System.Net.HttpClient in .NET 4.5, you can get the content returned by GetAsync using the HttpResponseMessage.Contentproperty as an HttpContent-derived object. You can then read the contents to a string using the HttpContent.ReadAsStringAsyncmethod or as a stream using the ReadAsStreamAsyncmethod.
如果您指的是 .NET 4.5 中的 System.Net.HttpClient,则可以使用HttpResponseMessage.Content属性作为HttpContent派生对象获取 GetAsync 返回的内容。然后,您可以使用HttpContent.ReadAsStringAsync方法将内容读取为字符串,或使用ReadAsStreamAsync方法将内容读取为流。
The HttpClientclass documentation includes this example:
的HttpClient的类文件包括该实施例中:
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
回答by Wouter Vanherck
Building on @Panagiotis Kanavos' answer, here's a working method as example which will also return the response as an object instead of a string:
基于@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;
}
Keep in mind that this is only an example and that you'd probably would like to use HttpClientas a shared instance instead of using it in a using-clause.
请记住,这只是一个示例,您可能希望将其HttpClient用作共享实例,而不是在 using 子句中使用它。
回答by James Heffer
What I normally do, similar to answer one:
我通常会做什么,类似于回答一:
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;
}
Where 'model' is your C# model class.
其中“模型”是您的 C# 模型类。
回答by Greg Z.
I think the shortest way is:
我认为最短的方法是:
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>();
回答by bulbul bd
It's working fine for me by the following way -
通过以下方式对我来说效果很好 -
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;
}

