Question

I've developed a website using Ruby on Rails, and I have product information stored in the website's database. How might I go about retrieving information about a specific product using a C# client application? I have my Product model set up with the following route:

resources :products

In C#, I've tried the following code to retrieve product information for a product whose ID is 32:

HttpWebRequest request = WebRequest.CreateHttp("http://127.0.0.1:3000/products/32");

request.Method = "GET";

WebResponse response = request.GetResponse();

String text;

using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
    text = reader.ReadToEnd();
}

However, this basically just stores the entire HTML code of the page in the "text" String. How would I be able to retrieve just the product information in XML or JSON format? I believe I need to make some changes in my Rails app, and I found a link from 2011 that recommends using RABL, but I'm not sure if there is a better way of creating an API.

Any help would be greatly appreciated!

Était-ce utile?

La solution

Thanks to Gusman's help, I've managed to figure it out!

I've changed my C# code to the following:

HttpWebRequest request = WebRequest.CreateHttp("http://127.0.0.1:3000/products/32.xml");

request.Method = "GET";

request.ContentType = "application/xml";

WebResponse response = request.GetResponse();

String text;

using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
    text = reader.ReadToEnd();
}

I added the ".xml" extension to the URL in the CreateHttp method. This way, the regular HTML page will not be loaded; only the XML page will be loaded. As a result of doing this, I had to handle the different format in Rails. Here's what the end of my "show" action in the Products controller looks like:

respond_to do |format|
  format.html
  format.xml { render :xml => @product }
end

This allows the handling of XML GET requests. I have yet to work on the POST part, but I'm assuming it wouldn't be too different.

Thanks again for all of the help!

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top