C # Call Baidu map Web Service API

Source: Internet
Author: User

Recently, the company needs to make some data recommendations based on the traffic routes and distances between the two locations. In order to ensure program stability and user experience, we want to collect data from the Baidu map API and save it to the database, after a thorough research, I selected the Direction API in the Baidu map Web Service API, and finally wrote a service for timed collection. For more information about the Direction API, go to the Baidu map API page and go to http://developer.baidu.com/map/direction-api.htm. I. Preparations 1. First, apply for a key and select a function based on your needs. Note that if you select the sn verification method for the request verification method, you need to input the sn parameter when requesting the Api address. As shown in: 2. The following table shows whether the request interface parameters must be formatted. For example, parameter meanings: origin: Baidu tower coordinate format: lat <latitude>, lng <longitude> name + latitude and longitude: baidu tower | 40.056878, 116.30815 start point name or latitude and longitude, or names and latitude and longitude can be provided at the same time. At this time, the priority of latitude and longitude is high and serves as the basis for navigation. The name is only used for display. Destination: required name: Tiananmen longitude and latitude: 39.915285, 116.403857 coordinate format: lat <latitude>, lng <longitude> name + latitude and longitude: Baidu tower | 40.056878, 116.30815 start point name or latitude and longitude, you can also provide the name and latitude and longitude at the same time. At this time, the priority of the latitude and longitude is high, and the name is only used for display. Mode (optional) The default value is driving (driving mode) Navigation mode, including driving, walking, and transit) this parameter is required when region is required for Beijing public transit and pedestrian navigation. Origin_region is required in the city where the Beijing start point is located. It is required for driving and navigation. Destination_region is required for the destination city of Beijing and required for driving and navigation. Output is optional. The default value is xml json, which indicates the output type. It can be set to xml or json. The default value is xml. Coord_type is optional. The default value is bd09ll gcj02 (which is used for the national test Bureau coordinates, such as google and soso maps). It is an optional parameter. The default value is bd09ll. Allowed values: bd09ll (Baidu longitude and latitude coordinates), bd09mc (Baidu mocato coordinates), gcj02 (CNAs encryption coordinates), and wgs84 (coordinates obtained by gps devices ). Waypoints (optional) kuike technology tower | a collection of Route points on a West ticket, including one or more address names or latitude and longitude separated by the vertical line character "|. Tactics selects the 11 navigation policy. The type of the navigation route. 10: No high speed; 11. Minimum Time; 12. Minimum path. The accesskey is required. The access permission sn of the e4805d16520de693a3fe707gj962045 user is required. If the user's access permission signature timestamp sn exists, the timestamp is required. It must be used with the sn. 3. How to use GET requests to collect API data request API: 1 // <summary> 2 // send API request and return solution information. 3 /// </summary> 4 /// <returns> </returns> 5 private static T RequestApi <T> (string origin, string origin_region, string destination, string destination_region, string mode) 6 {7 string apiUrl = "http://api.map.baidu.com/direction/v1"; 8 // string ak = "e4805d16520de693a3fe707gj962045"; 9 string apiKey = "Courier "; // 10 string output = "json"; 11 // string origin_region = "North Beijing "; 12 // string origin =" Tsinghua University "; 13 // string destination =" Peking University "; 14 // string destination_region =" Beijing "; 15 // string mode = "driving"; 16 IDictionary <string, string> param = new Dictionary <string, string> (); 17 param. add ("ak", apiKey); 18 param. add ("output", output); 19 if (mode = "driving") 20 {21 param. add ("origin_region", origin_region); 22 param. add ("destination_region", destination_region); 23} 24 els E25 {26 param. add ("region", origin_region); 27} 28 29 param. add ("origin", origin); 30 param. add ("destination", destination); 31 param. add ("mode", mode); 32 33 string result = string. empty; 34 35 // initialize the entity class of solution information. 36 T info = default (T); 37 try38 {39 // request the Api address in the form of Get 40 result = HttpUtils. doGet (apiUrl, param); 41 info = JsonHelper. fromJsonTo <T> (result); 42} 43 catch (Exception) 44 {45 info = default (T); 46 throw; 47} 48 49 return info; 50} HttpUtils class: view code 1 // <summary> 2 // provides Http-related methods. 3 /// </summary> 4 public class HttpUtils 5 {6 7 /// <summary> 8 // execute the http get request. 9 /// </summary> 10 /// <param name = "url"> request address </param> 11 /// <param name = "parameters"> Request parameters </param> 12 // <returns> HTTP Response </returns> 13 public static string DoGet (string url, IDictionary <string, string> parameters) 14 {15 if (parameters! = Null & parameters. Count> 0) 16 {17 if (url. Contains ("? ") 18 {19 url = url +" & "+ BuildPostData (parameters); 20} 21 else 22 {23 url = url + "? "+ BuildPostData (parameters); 24} 25} 26 27 HttpWebRequest req = (HttpWebRequest) WebRequest. create (url); 28 req. servicePoint. expect100Continue = false; 29 req. method = "GET"; 30 req. keepAlive = true; 31 req. userAgent = "Test"; 32 req. contentType = "application/x-www-form-urlencoded; charset = UTF-8"; 33 34 HttpWebResponse rsp = null; 35 try 36 {37 rsp = (HttpWebResponse) req. getResponse (); 38} 39 Catch (WebException webEx) 40 {41 if (webEx. Status = WebExceptionStatus. Timeout) 42 {43 rsp = null; 44} 45} 46 47 if (rsp! = Null) 48 {49 if (rsp. CharacterSet! = Null) 50 {51 Encoding encoding = Encoding. getEncoding (rsp. characterSet); 52 return GetResponseAsString (rsp, encoding); 53} 54 else 55 {56 return string. empty; 57} 58} 59 else 60 {61 return string. empty; 62} 63} 64 65 // <summary> 66 // convert the response to text. 67 // </summary> 68 // <param name = "rsp"> response Stream object </param> 69 // <param name = "encoding"> encoding method </param> 70 // <returns> response text </returns> 71 private static string GetResponseAsString (HttpWebResponse rsp, encoding encoding) 72 {73 StringBuilder result = new StringBuilder (); 74 Stream stream = null; 75 StreamReader reader = null; 76 77 try 78 {79 // read HTTP Response 80 stream = rsp in response stream mode. getResponseStream (); 81 Reader = new StreamReader (stream, encoding); 82 83 // each read cannot exceed 256 characters, and write the string 84 char [] buffer = new char [256]; 85 int readBytes = 0; 86 while (readBytes = reader. read (buffer, 0, buffer. length)> 0) 87 {88 result. append (buffer, 0, readBytes); 89} 90} 91 catch (WebException webEx) 92 {93 if (webEx. status = WebExceptionStatus. timeout) 94 {95 result = new StringBuilder (); 96} 97} 98 finally 9 9 {100 // release resource 101 if (reader! = Null) reader. Close (); 102 if (stream! = Null) streams. Close (); 103 if (rsp! = Null) rsp. Close (); 104} 105 106 return result. ToString (); 107} 108 109 // <summary> 110 // assemble common text request parameters. 111 /// </summary> 112 // <param name = "parameters"> request parameter dictionary in Key-Value format. </Param> 113 // <returns> URL-encoded request data. </Returns> 114 private static string BuildPostData (IDictionary <string, string> parameters) 115 {116 StringBuilder postData = new StringBuilder (); 117 bool hasParam = false; 118 119 IEnumerator <KeyValuePair <string, string> dem = parameters. getEnumerator (); 120 while (dem. moveNext () 121 {122 string name = dem. current. key; 123 string value = dem. current. value; 124 // ignore the 125 if (! String. IsNullOrEmpty (name )&&! String. isNullOrEmpty (value) 126 {127 if (hasParam) 128 {129 postData. append ("&"); 130} 131 132 postData. append (name); 133 postData. append ("="); 134 postData. append (Uri. escapeDataString (value); 135 hasParam = true; 136} 137} 138 139 return postData. toString (); 140} 141 142} The traffic data of two locations can be obtained by calling RequestApi cyclically. Json converted object classes can be directly generated using the json2csharp tool at http://json2csharp.com /. 2. Note: 1. This API sometimes takes a long response time after a request and often times out. Therefore, I throw a WebException exception in the HttpUtils class. 2. handle exceptions in the Json conversion method.

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.