original text http://developer.yahoo.com/dotnet/howto-rest_cs.html

The .NET Framework provides classes for performing HTTP requests. This HOWTO describes how to perform both GET and POST requests.

Overview

The System.Net namespace contains the HttpWebRequest and HttpWebResponse classes which fetch data from web servers and HTTP based web services. Often you will also want to add a reference to System.Web which will give you access to the HttpUtility class that provides methods to HTML and URL encode and decode text strings.

Yahoo! Web Services return XML data. While some web services can also return the data in other formats, such as JSON and Serialized PHP, it is easiest to utilize XML since the .NET Framework has extensive support for reading and manipulating data in this format.

Simple GET Requests

The following example retrieves a web page and prints out the source.

C# GET Sample 1

  1. using System;
  2. using System.IO;
  3. using System.Net;
  4. using System.Text;
  5. // Create the web request
  6. HttpWebRequest request = WebRequest.Create("http://developer.yahoo.com/") as HttpWebRequest;
  7. // Get response
  8. using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
  9. {
  10. // Get the response stream
  11. StreamReader reader = new StreamReader(response.GetResponseStream());
  12. // Console application output
  13. Console.WriteLine(reader.ReadToEnd());
  14. }

Simple POST Requests

Some APIs require you to make POST requests. To accomplish this we change the request method and content type and then write the data into a stream that is sent with the request.

C# POST Sample 1

  1. // We use the HttpUtility class from the System.Web namespace
  2. using System.Web;
  3. Uri address = new Uri("http://api.search.yahoo.com/ContentAnalysisService/V1/termExtraction");
  4. // Create the web request
  5. HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
  6. // Set type to POST
  7. request.Method = "POST";
  8. request.ContentType = "application/x-www-form-urlencoded";
  9. // Create the data we want to send
  10. string appId = "YahooDemo";
  11. string context = "Italian sculptors and painters of the renaissance"
  12. + "favored the Virgin Mary for inspiration";
  13. string query = "madonna";
  14. StringBuilder data = new StringBuilder();
  15. data.Append("appid=" + HttpUtility.UrlEncode(appId));
  16. data.Append("&context=" + HttpUtility.UrlEncode(context));
  17. data.Append("&query=" + HttpUtility.UrlEncode(query));
  18. // Create a byte array of the data we want to send
  19. byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
  20. // Set the content length in the request headers
  21. request.ContentLength = byteData.Length;
  22. // Write data
  23. using (Stream postStream = request.GetRequestStream())
  24. {
  25. postStream.Write(byteData, 0, byteData.Length);
  26. }
  27. // Get response
  28. using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
  29. {
  30. // Get the response stream
  31. StreamReader reader = new StreamReader(response.GetResponseStream());
  32. // Console application output
  33. Console.WriteLine(reader.ReadToEnd());
  34. }

HTTP Authenticated requests

The del.icio.us API requires you to make authenticated requests, passing your del.icio.us username and password using HTTP authentication. This is easily accomplished by adding an instance of NetworkCredentials to the request.

C# HTTP Authentication

  1. // Create the web request
  2. HttpWebRequest request
  3. = WebRequest.Create("https://api.del.icio.us/v1/posts/recent") as HttpWebRequest;
  4. // Add authentication to request
  5. request.Credentials = new NetworkCredential("username", "password");
  6. // Get response
  7. using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
  8. {
  9. // Get the response stream
  10. StreamReader reader = new StreamReader(response.GetResponseStream());
  11. // Console application output
  12. Console.WriteLine(reader.ReadToEnd());
  13. }

Error Handling

Yahoo! offers many REST based web services but they don't all use the same error handling. Some web services return status code 200 (OK) and a detailed error message in the returned XML data while others return a standard HTTP status code to indicate an error. Please read the documentation for the web services you are using to see what type of error response you should expect. Remember that HTTP Authentication is different from the Yahoo! Browser-Based Authentication.

Calling HttpRequest.GetResponse() will raise an exception if the server does not return the status code 200 (OK), the request times out or there is a network error. Redirects are, however, handled automatically.

Here is a more full featured sample method that prints the contents of a web page and has basic error handling for HTTP error codes.

C# GET Sample 2

  1. public static void PrintSource(Uri address)
  2. {
  3. HttpWebRequest request;
  4. HttpWebResponse response = null;
  5. StreamReader reader;
  6. StringBuilder sbSource;
  7. if (address == null) { throw new ArgumentNullException("address"); }
  8. try
  9. {
  10. // Create and initialize the web request
  11. request = WebRequest.Create(address) as HttpWebRequest;
  12. request.UserAgent = ".NET Sample";
  13. request.KeepAlive = false;
  14. // Set timeout to 15 seconds
  15. request.Timeout = 15 * 1000;
  16. // Get response
  17. response = request.GetResponse() as HttpWebResponse;
  18. if (request.HaveResponse == true && response != null)
  19. {
  20. // Get the response stream
  21. reader = new StreamReader(response.GetResponseStream());
  22. // Read it into a StringBuilder
  23. sbSource = new StringBuilder(reader.ReadToEnd());
  24. // Console application output
  25. Console.WriteLine(sbSource.ToString());
  26. }
  27. }
  28. catch (WebException wex)
  29. {
  30. // This exception will be raised if the server didn't return 200 - OK
  31. // Try to retrieve more information about the network error
  32. if (wex.Response != null)
  33. {
  34. using (HttpWebResponse errorResponse = (HttpWebResponse)wex.Response)
  35. {
  36. Console.WriteLine(
  37. "The server returned '{0}' with the status code {1} ({2:d}).",
  38. errorResponse.StatusDescription, errorResponse.StatusCode,
  39. errorResponse.StatusCode);
  40. }
  41. }
  42. }
  43. finally
  44. {
  45. if (response != null) { response.Close(); }
  46. }
  47. }

Further reading

Related information on the web.

Make Yahoo! Web Service REST Calls With C# More articles about

  1. [ turn ]Web Service Authentication

    In this paper, from :http://www.codeproject.com/Articles/9348/Web-Service-Authentication Download source files - 45. ...

  2. [ turn ]Calling Web Service Functions Asynchronously from a Web Page Asynchronous call WebServices

    In this paper, from :http://www.codeproject.com/Articles/70441/Calling-Web-Service-Functions-Asynchronously-from Ove ...

  3. Using UTL_DBWS to Make a Database 11g Callout to a Document Style Web Service

    In this Document   _afrLoop=100180147230187&id=841183.1&displayIndex=2&_afrWindowMode=0& ...

  4. Summary of Amazon Marketplace Web Service

    Overview Here I want to summarize Amazon marketplace web service (MWS or AMWS) that can be used for ...

  5. REST and SOAP Web Service Comparison of differences

    This article is reprinted from someone else's blog ,ArcGIS Server Launched Yes SOAP and REST Two interfaces ( Using interface types may not be accurate ) Type of support , This paper makes a very clear comparison between SOAP and Rest The difference between ! ///////// ...

  6. turn :Web service What is it? ?

    author :  Ruan Yifeng In my submission , The next generation of Internet software will be built on Web service( That is to say " cloud ") On the basis of . I put my study notes and learning experience , Put it on the blog , Welcome to correct . Today, let's write a basic question ,Web ...

  7. 【 Reprint 】Using the Web Service Callbacks in the .NET Application

    source This article describes a .NET Application model driven by the Web Services using the Virtual Web ...

  8. turn -Web Service There are three send and accept protocols in SOAP、http get、http post

    Link to the original text :web There are three send accept protocols in the service SOAP/HTTP GET/HTTP POST One .web There are three send accept protocols in the service SOAP/HTTP GET/HTTP POST stay web In service , There are three options ...

  9. C# Web Service Elementary teaching

    Original link :http://www.codeproject.com/cs/webservices/myservice.asp author :Chris Maunder Introduction Creating y ...

Random recommendation

  1. use SVN check out Third party library lost after the project

    Used to Cornerstone check out A project comes down , But the third party .a The library is always missing , Project report error , After research, the following solutions have been found : First ,Xcode Default ignore .a file . So it can't be submitted to svn The server , But it is ...

  2. ionic+angular+cordova Android environment construction

    1.java Environment configuration download java jdk Baidu search java jdk After installation cmd Window type Java -version The installation is successful . And then put java jdk Configure to environment variables . (1) choice [ New Department ...

  3. QQ Object oriented design

          Communication projects -- Imitation QQ Chat program   Detailed design specification                                                         One . introduction This project is to verify Jav ...

  4. Android notifications The use of the notification bar

    app Send notification messages to key codes and click events in the notification bar : package com.example.notifications; import android.os.Bundle; import androi ...

  5. vb call exe file

    vb call exe file function :Call Shell(PathName,WindowStyle) or a = Shell(PathName,WindowStyle) , No declaration required . annotation :PathName ...

  6. ZeroMQ/jzmq Install and use

    Environmental Science : No LSB modules are available. Distributor ID: Ubuntu Description: Ubuntu 12.04.2 LTS Release: 12 ...

  7. Windows Azure Community news review (#70 edition )

    Welcome to the latest version of the weekly review , It's about cloud computing and Windows Azure Community driven news . Content and dialogue . Here's what you've gathered in the past week based on your feedback : article . Videos and blog posts ·    How to choose No ...

  8. SQL Server Way of learning ( 3、 ... and ):“ Additions and deletions ” And “ increase ”

    0. Catalog 1. Preface 2. adopt SSMS Add data 3. adopt SQL Statement to add data 3.1 Add a single piece of data 3.2 Add multiple pieces of data 4. Import data from other tables 4.1 Import data from other tables in the database 4.2 adopt exce ...

  9. P5270 No matter what, Lord Shenshu will delete the library and run away

    Title address :P5270 No matter what, Lord Shenshu will delete the library and run away At first glance, it looks like a simulation , It seems to be \(O(n)\) Of Water problem Finish it with confidence : #include <bits/stdc++.h> using ...

  10. GinKgoCTF-Misc

    One : Who moved my school badge ? Jpg Change txt——> seek ——>GKCTF{This_is_a_huaji} Two : Strange compression package 1 A six digit password is not secure at all !!!!!! Download zip ——> Password ( ...