[c#] HTTP 요청에서 JSON 데이터를 다시 받기

제대로 작동하는 웹 요청이 있지만 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);
}



답변

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

이것은 단지 예일 뿐이며 HttpClientusing 절에서 사용하는 대신 공유 인스턴스 로 사용하고 싶을 것입니다 .


답변

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


답변

가장 짧은 방법은 다음과 같습니다.

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


답변

내가 일반적으로하는 일, 대답과 비슷합니다.

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

여기서 ‘model’은 C # 모델 클래스입니다.


답변

다음과 같은 방식으로 잘 작동합니다.

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


답변