从HTTP请求接收JSON数据

时间:2012-06-07 08:45:52

标签: 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;

api get方法

//Cut out alot of code but you get the idea
public string Get()
{
    return JsonConvert.SerializeObject(returnedPhoto);
}

6 个答案:

答案 0 :(得分:101)

如果您在.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();

答案 1 :(得分:10)

从Microsoft System.Net.Http.Json安装此nuget软件包。它包含扩展方法。

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

现在,您将能够看到以下方法:

enter image description here

因此您现在可以执行以下操作:

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

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

答案 2 :(得分:9)

@Panagiotis Kanavos 的答案为基础,以下是一个有效的方法示例,该方法还将返回响应作为对象而不是字符串:

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用作共享实例,而不是在使用子句中使用它。

答案 3 :(得分:1)

我认为最简单的方法是:

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

答案 4 :(得分:0)

我通常做的,类似于回答一个:

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

答案 5 :(得分:0)

通过以下方式对我来说效果很好-

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