简体   繁体   English

从 HTTP 请求接收 JSON 数据

[英]Receiving JSON data back from HTTP request

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.我有一个正常工作的 web 请求,但它只是返回状态正常,但我需要 object 我要求它返回。 I am not sure how to get the json value I am requesting.我不确定如何获得我要求的 json 值。 I am new to using the object HttpClient, is there a property I am missing out on?我是使用 object HttpClient 的新手,是否有我遗漏的属性? I really need the returning object.我真的需要返回的 object。 Thanks for any help谢谢你的帮助

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);
}

If you are referring to the System.Net.HttpClient in .NET 4.5, you can get the content returned by GetAsync using the HttpResponseMessage.Content property as an HttpContent -derived object.如果您指的是 .NET 4.5 中的 System.Net.HttpClient,则可以使用HttpResponseMessage.Content属性作为HttpContent派生对象获取 GetAsync 返回的内容。 You can then read the contents to a string using the HttpContent.ReadAsStringAsync method or as a stream using the ReadAsStreamAsync method.然后,您可以使用HttpContent.ReadAsStringAsync方法将内容读取为字符串,或使用ReadAsStreamAsync方法将内容读取为流。

The HttpClient class 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();

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 HttpClient as a shared instance instead of using it in a using-clause.请记住,这只是一个示例,您可能希望将HttpClient用作共享实例,而不是在 using 子句中使用它。

Install this nuget package from Microsoft System.Net.Http.Json .从 Microsoft System.Net.Http.Json安装这个 nuget 包。 It contains extension methods.它包含扩展方法。

Then add using System.Net.Http.Json然后using System.Net.Http.Json添加

Now, you'll be able to see these methods:现在,您将能够看到这些方法:

在此处输入图片说明

So you can now do this:所以你现在可以这样做:

await httpClient.GetFromJsonAsync<IList<WeatherForecast>>("weatherforecast");

Source: https://www.stevejgordon.co.uk/sending-and-receiving-json-using-httpclient-with-system-net-http-json来源: https : //www.stevejgordon.co.uk/sending-and-receiving-json-using-httpclient-with-system-net-http-json

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>();

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;
    }

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# 模型类。

The code below is to access your HttpResponseMessage and extract your response from HttpContent.下面的代码用于访问您的 HttpResponseMessage 并从 HttpContent 中提取您的响应。

string result = ret.Result.Content.ReadAsStringAsync().Result;

Convert your json in a structure according with your business In my case BatchPDF is a complex object that it is being populated by result variable.根据您的业务将您的 json 转换为结构在我的情况下,BatchPDF 是一个复杂的 object,它由结果变量填充。

BatchPDF batchJson = JsonConvert.DeserializeObject<BatchPDF>(result);

return batchJson;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM