Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get response from web API call

I have an API that I want to call and get the response back. Then I want to assign that response to a variable.

I have an API like:

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

When I run this URL in a browser, it prints an SMS balance. I want this SMS balance as a response and then assign it to a variable in my page.

like image 266
Vivek Parikh Avatar asked Dec 03 '22 06:12

Vivek Parikh


2 Answers

You may also use WebRequest class.

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

Of course, you can change Console.WriteLine to whatever you want to do with response.

like image 95
Iarek Avatar answered Dec 14 '22 15:12

Iarek


Your service is an .aspx page which just returns text (the sms balance) and no html? If so you can 'scrape it'

string urlData = String.Empty;
WebClient wc = new WebClient();
urlData = wc.DownloadString("http://domainname/Webservicesms_get_userbalance.aspx?user=xxxx&passwd=xxxx");
like image 26
Neil Thompson Avatar answered Dec 14 '22 17:12

Neil Thompson