2016-10-05 4 views
0

API 테스트가 처음인데 C#에서 요청한 응답을 읽을 수있는 방법을 알고 싶습니다. 나는 아래에서 그것을 시험해 보았다.API 요청을 보내고 Json 응답을 얻는 방법 C#

예를 들어 나는 API URL을 가지고있다 - http://api.test.com/api/xxk/jjjj?limit=30 나에게 응답을주고있다

  HttpWebRequest request = WebRequest.Create("http://api.test.com/api/xxk/jjjj?limit=30") as HttpWebRequest; 
      using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) 
      { 

       var res = response; 
      } 

하지만 난 모든 JSON 응답 결과를 얻을 필요하고 그것을 위해 값에 액세스해야합니다.

응답을 위해 디버그 모드를 체크 인 할 때 모든 응답 값을 볼 수 없습니다. 또한 어떤 oject가 저에게 모든 가치를 줄 것입니까? 나는 내가 틀린 일을하고 있다고 확신하지만, 누군가가 나를 도와 주면 위대한 사람이 될 것이라고 알 것입니다.

답변

2

응답의 httpBody를받는 방법에 대한 자세한 설명은 https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.getresponse(v=vs.110).aspx을 확인하십시오. .getResponse()를 사용하여 응답을 얻은 후에는 응답 스트림을 가져 와서 변수에서 그 내용을 읽을 수 있습니다. 링크 문서에서 언급 한 바와 같이

는 :

 HttpWebRequest request = (HttpWebRequest)WebRequest.Create (args[0]); 
     HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 

     Console.WriteLine ("Content length is {0}", response.ContentLength); 
     Console.WriteLine ("Content type is {0}", response.ContentType); 

     // Get the stream associated with the response. 
     Stream receiveStream = response.GetResponseStream(); 

     // Pipes the stream to a higher level stream reader with the required encoding format. 
     StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8); 

     Console.WriteLine ("Response stream received."); 
     Console.WriteLine (readStream.ReadToEnd()); 
     response.Close(); 
     readStream.Close(); 

출력은 다음과 같습니다

/* 
The output from this example will vary depending on the value passed into Main 
but will be similar to the following: 

Content length is 1542 
Content type is text/html; charset=utf-8 
Response stream received. 
<html> 
... 
</html> 

*/ 

으로 :

var res = response.GetResponseStream().ReadToEnd(); 

당신은 문자열 표현으로 JSON 본문을 얻을 것이다. 그런 다음 Newtonsoft.JSON과 같은 json 파서를 사용하여 파싱 할 수 있습니다.

이 질문에 적어도 70 %의 답변이되기를 바랍니다. JSON 본문을 자동으로 구문 분석하는 API를 작성하는 방법이 있다고 생각합니다 (적어도 새로운 net core (mvc vnext)와 함께). 나는이 방법을 정확하게 기억해야만한다.

관련 문제