2011-09-30 7 views
4

API를 호출하고 응답을 다시 가져 오려고합니다. 그런 다음 해당 응답을 변수에 지정하려고합니다.웹 API 호출에서 응답을 얻는 방법

내가 같은 API가 : 나는 브라우저에서 URL을 실행하면

http://example.org/Webservicesms_get_userbalance.aspx?user=xxxx&passwd=xxxx 

를, 그것은 SMS의 균형을 인쇄합니다. 이 SMS 잔액을 응답으로 설정 한 다음 내 페이지의 변수에 할당합니다.

+0

아약스 전화로 작업 완료 될 수 있습니다 ... –

+0

@Yves M 설명해 주시겠습니까 ?? –

+0

무엇을 시도 했습니까? 어떤 부분에서 문제가 있습니까? 비어있는 검색 용어는 무엇입니까? 이 정보를 추가하려면 질문을 편집하여 응답하십시오 ... –

답변

6

귀하의 서비스는 단지 텍스트 (sms balance)와 html이없는 .aspx 페이지입니까? 그래서 당신은 '을 긁어'수 경우

string urlData = String.Empty; 
WebClient wc = new WebClient(); 
urlData = wc.DownloadString("http://domainname/Webservicesms_get_userbalance.aspx?user=xxxx&passwd=xxxx"); 
6

또한 WebRequest 클래스를 사용할 수 있습니다. 물론

WebRequest request = WebRequest.Create ("http://domainname/Webservicesms_get_userbalance.aspx?user=xxxx&passwd=xxxx"); 

// Get the response. 
HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 

// Get the stream containing content returned by the server. 
Stream dataStream = response.GetResponseStream(); 
// Open the stream using a StreamReader for easy access. 
StreamReader reader = new StreamReader (dataStream); 
// Read the content. 
string responseFromServer = reader.ReadToEnd(); 
// Display the content. 
Console.WriteLine (responseFromServer); 
// Cleanup the streams and the response. 
reader.Close(); 
dataStream.Close(); 
response.Close(); 

, 당신은 당신이 응답 할 원하는에 Console.WriteLine을 변경할 수 있습니다.

+0

+1; 이것은 내가 보아온 더 일반적인 예일 것입니다. 그런데 왜 닐이 준 대답보다 우월한가? 이전 코드에서 작동합니까? 이 기능을 작동시키기 위해 포함해야 할 어셈블리가 더 적습니까? –

+0

@ MerlynMorgan-Graham 내 대답이 Neil 's보다 우수하다고 생각하지 마십시오. 한 가지는 WebClient가 STA 스레드를 실행해야한다고 말할 수 있습니다. WebRequest는 .NET 4, 3.5, 3.0, 2.0, 1.1, 1.0에서 지원되므로 제대로 작동해야합니다. –

+0

DownloadString을 사용할 때보 다 더 빠르게 느껴집니다. – Animesh

관련 문제