C # Network programming through the Watercress API access to book information (a)

Source: Internet
Author: User
Tags xpath

This article is mainly about how to get a book through the Watercress API information, initially see this content my initial idea is in the " C # Network Programming Web page simple download implementation "through the HttpWebResponse class to download the source code, and then through the regular expression analysis to get the node tag to get information." But later found it possible to pass Watercress API provides the programming interface implementation.
This article is only a basic C # network programming article, tried to test the next Watercress API, and no advanced content. But I hope it will be helpful for you to learn.
(Warning: Article for reference only, provide an idea, otherwise visit multiple times-10 times by 403 forbidden. Recommended authentication using the Watercress API)

I. Introduction to the Watercress API

before development you need to apply to create an app to get a new API Key (uniquely identifying your connect site and API consumer).
Just like the Watercress API QuickStart ( http://www.douban.com/service/apidoc/guide " example: This example shows the use of the API to get the information of the book ID 1220562, the URL of the request is as follows (note that {Yourapikey} is replaced with your API Key).
http://api.douban.com/book/subject/1220562 APIKEY={YOURKEYAPI}
The XML document returned is as follows:

<?xml version= "1.0" encoding= "UTF-8"? ><entry xmlns= "Http://www.w3.org/2005/Atom" xmlns:db= "http// www.douban.com/xmlns/"xmlns:gd=" http://schemas.google.com/g/2005 "xmlns:opensearch=" http://a9.com/-/spec/ opensearchrss/1.0/"xmlns:opensearch=" http://a9.com/-/spec/opensearchrss/1.0/"><id>http:// Api.douban.com/book/subject/1220562</id><title> Full Moon night Moby Dick now </title><category scheme= "/http Www.douban.com/2007#kind "term=" Http://www.douban.com/2007#book "/><author><name>[Day" piece Shan Gong yi </name ></author><link href= "http://api.douban.com/book/subject/1220562" rel= "self"/><link href= "http ://book.douban.com/subject/1220562/"rel=" alternate "/><link href=" http://img3.douban.com/spic/s1747553.jpg "Rel=" image "/><link href=" http://m.douban.com/book/subject/1220562/"rel=" mobile "/><summary> that year, It was a year of listening to Mozart, bass fishing and family breakdown. When it comes to family rupture, the mother blames herself for not finding a good man, but the father thought it was the mother who was fascinated by the fox, but the problem was the father. </summary><db:attribute name= "Isbn10" >7543632608</db:attribute><db:attribute name= "Isbn13" >9787543632608</db:attribute><db:attribute Name= "title" > Full Moon Night Moby </db:attribute><db:attribute name= "pages" &GT;180&LT;/DB:ATTRIBUTE&GT;&LT;DB: Attribute name= "Translator" > Yu </db:attribute><db:attribute name= "Author" >[Day] pian Shan Gong yi </db:attribute ><db:attribute name= "Price" >15.00 yuan </db:attribute><db:attribute name= "publisher" > Qingdao Publishing House </ Db:attribute><db:attribute name= "Binding" > Paperback </db:attribute><db:attribute name= "pubdate" > 2005-1</db:attribute><db:tag count= "Name=" "/><db:tag count=" Name= "Japan"/><db:tag Count= "name=", "Japanese literature"/><db:tag count= "Name=" "novel"/><db:tag count= "to" Name= "Full Moon night White whale Now"/><db:tag Count= "Name=" "Love"/><db:tag count= "8" name= "Pure Love"/><db:tag count= "8" name= "Foreign literature"/><gd:rating Average= "7.0" max= "min=" 0 "numraters=" 322 "/></entry>

At this point, all I need to do is get the data from the returned XML through the input URL, get the HTTP request and the reply via HttpWebRequest and HttpWebResponse, and parse the information in the XML (more difficult). Then I realized that if I wanted to experiment with the API, Watercress is allowed to make API calls without applying API key (no more than 10 requests per minute). That is, I enter the URL in the program as follows to return the XML.
http://api.douban.com/book/subject/1220562

two. C # get Watercress book information

1. Add a Namespace

Using System.Net;                      Httpusing System.IO;                       File stream operation using System.Text.RegularExpressions;  The regular expression using System.Xml;                      XML document

2. Add a button click event

Click the button "Get information" private void button1_click (object sender, EventArgs e) {    richtextbox1.clear ();    Gets the URL of the input    string url = textBox1.Text.ToString ();    HttpWebRequest Object instance: This class is used to get and manipulate HTTP requests to create WebRequest objects    HttpWebRequest request = (HttpWebRequest) webrequest.create (URL);    HttpWebResponse Object instance: This class is used to get and manipulate HTTP reply     httpwebresponse response = (HttpWebResponse) request. GetResponse ();    Constructs a byte stream    StreamReader reader = new StreamReader (response. GetResponseStream ());    Stream read from head to tail    string xmlUrl = reader. ReadToEnd ();    Reader. Close ();    Response. Close ();    Call the custom function to get the XML information    getinfoxml (XMLURL);}

3. Custom functions for book information

Gets the watercress XML content and displays the private void Getinfoxml (string xmlUrl) {try {//instance XML document XmlDocument xmldoc = new XMLDOCU        ment ();                               Loads the XML document Xmldoc.loadxml (XMLURL) from the specified string;        Instance parsing, adding and removing namespaces and scope Management for collections XmlNamespaceManager XMLNM = new XmlNamespaceManager (xmldoc.nametable);        Adds the given namespace to the collection Xmlnm.addnamespace ("db", "Http://www.w3.org/2005/Atom");        Gets the document root element XmlElement root = xmldoc.documentelement; Select a node list//function prototype that matches an XPath (content) Expression: selectnodes (String Xpath,xmlnamespacemanger nsmgr) XmlNodeList nodes = root.        SelectNodes ("/db:entry", XMLNM); Get child node information foreach (XmlNode nodedata in nodes) {foreach (XmlNode childnode in Nodedata.childnodes ) {string str = Childnode.                Name; Switch (str) {case "title": String name = "Title Name:" + Childnode.                     InnerText + "\r\n\r\n";   Richtextbox1.appendtext (name);                                        Break Case "Author": String author = "" + Childnode.                        InnerText + "\r\n\r\n";                        Richtextbox1.appendtext (author);                    Break                            Case "Db:attribute": {//Get <db:attribute name= "XXX" > Properties Switch (childnode. Attributes[0].  Value) {case "pages": string Pages= "Total Pages:" +childnode.                                    innertext+ "\r\n\r\n";                                    Richtextbox1.appendtext (pages);                                Break Case "Prices": String price= "Price:" +childnode.                                    innertext+ "\r\n\r\n";                                    Richtextbox1.appendtext (price);           Break                     Case "publisher": String publisher= "Publisher:" +childnode.                                    innertext+ "\r\n\r\n";                                    Richtextbox1.appendtext (publisher);                                Break Case "pubdate": String pubdate= "published date:" +childnode.                                    innertext+ "\r\n\r\n";                                    Richtextbox1.appendtext (pubdate);                            Break                        } break; } case "Summary"://display content WordWrap set to True wrap (no need to call SP Lit function or character length) string summary= "content:" +childnode.                                                        innertext+ "\r\n\r\n";                                                     Richtextbox1.appendtext (summary);                    Break Case "link"://Node attribute is atTributes[0] fails to get the IF (Childnode. ATTRIBUTES[1]. Value = = "image") {//Get image path <link rel= "image" href= "http://xxx.jp G "/> String imagePath = Childnode. Attributes[0].                            Value;                            Download picture String imageName = "Local.jpg";                            System.Net.WebClient client = new System.Net.WebClient ();                            Download the specified URL resource to the local Folder//function prototype DownloadFile (string address,string fileName) Client.                            DownloadFile (Imagepath,imagename);                            Load picture from local file This.pictureBox1.Image = Image.FromFile (imageName);                            Image Original Size this.pictureBox1.SizeMode = Pictureboxsizemode.zoom; When downloading the second picture, there is always "an exception occurred during the WebClient request"} break;                }//switch}//foreach}//foreach} catch (Exception msg)//exception handling {Mess Agebox.show (Msg.    Message); }}//getinfoxml

4. The results of the operation are as follows


The book information in the source URL is described in the following example:

three. Problems encountered and summary

I can find the URL I entered without the API key, but I always use it when I am testing. And then I have some problems:
1. The Watercress API to get the book information interface, need to pass Subjectid or Isbnid (ISBN), but I want to achieve is only know the title, can get the information of the book, rather than just pass in a string of URLs, these analysis all let the program content implementation, this is the next need to do.
2. When downloading a picture using WebClient and DownloadFile (string address,string fileName), when getting the second picture always prompts the error "WebClient the request occurred during the exception", do not know why, But do not want to use stream or concurrent to get pictures, just want to know why this is?
3. This is only a basic introduction to the use of the Watercress API article, the current watercress for the authorized users (development API using the OAuth protocol authentication) can achieve a lot of functions, later if there is time to write some "view user information, user's neighbor information, add and revise user collection, view Comments" article.
finally hope that the article is helpful to everyone, if there are errors or shortcomings in the article, please Haihan. At the same time, the article also referred to some information, thanks to these authors.
(By:eastmount 2014-5-2 3 o'clock in the afternoon original:Http://blog.csdn.net/eastmount)
Resources:
1. Quick start of the Watercress API
Http://www.douban.com/service/apidoc/guide
2.c# using watercress api-sun8134
Thank you very much for this article, in parsing XML I use the Selectsinglenodes method failed, referring to his method, also recommend everyone to read
Http://www.cnblogs.com/sun8134/archive/2010/12/15/1906879.html
3. Watercress Client-zh19900207 This article has only interface, but also I want to implement the function description
http://blog.csdn.net/zh19900207/article/details/8586000
4.XmlNode.SelectNodes method
Http://msdn.microsoft.com/zh-cn/library/4bektfx9.aspx

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.