[ELMA3] Примеры работы с WebAPI
Использование сторонних API позволяет существенно расширить функционал системы. В статье ниже рассмотрены 2 примера по работе с GET и POST-запросами.
В большинстве случаев сервисы являются платными, однако предоставляется возможность создавать несколько тысяч бесплатных запросов в месяц, чего вполне достаточно для небольшой или средней компании.
1. POST-запрос
Для примера воспользуемся API сервисом dadata.ru - один из методов позволяет получить адрес юридического лица или ИП по ИНН/ОГРН (https://dadata.ru/api/find-party/).
Для начала работы с сервисом необходимо пройти регистрацию и получить токен авторизации.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | //указываем url, к которому будем обращаться //генерация запроса HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest; req.Method = "POST" ; req.Timeout = 10000; req.Headers.Add( "Authorization" , "Token 92********************************ce" ); //указываем токен, полученный при регистрации req.ContentType = "application/json" ; req.Accept = "application/json" ; //данные для отправки var sentData = Encoding.UTF8.GetBytes( "{ \"query\": \"" +context.OGRN+ "\" }" ); //т.к. тело запроса небольшое, генерируем его строкой req.ContentLength = sentData.Length; Stream sendStream = req.GetRequestStream(); sendStream.Write(sentData, 0, sentData.Length); //получение ответа var res = req.GetResponse() as HttpWebResponse; var resStream = res.GetResponseStream(); var sr = new StreamReader(resStream, Encoding.UTF8); |
Для более простой обработки полученный ответ можно десериализовать. Для этого можно воспользоваться сторонним сервисом, например http://json2csharp.com.
Сохраним полученный ответ в строку, например:
1 | var context.Log = sr.ReadToEnd(); |
Полученную строку вставим в поле http://json2csharp.com. После нажатия кнопки Generate скопируем полученные классы в сценарий вне тела метода, в данном случае полученный ответ будет следующим:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 | public class Management { public string name { get ; set ; } public string post { get ; set ; } } public class State { public string status { get ; set ; } public long actuality_date { get ; set ; } public long registration_date { get ; set ; } public object liquidation_date { get ; set ; } } public class Opf { public object type { get ; set ; } public string code { get ; set ; } public string full { get ; set ; } public string @ short { get ; set ; } } public class Name { public string full_with_opf { get ; set ; } public string short_with_opf { get ; set ; } public object latin { get ; set ; } public string full { get ; set ; } public string @ short { get ; set ; } } public class Data2 { public string postal_code { get ; set ; } public string country { get ; set ; } public string region_fias_id { get ; set ; } public string region_kladr_id { get ; set ; } public string region_with_type { get ; set ; } public string region_type { get ; set ; } public string region_type_full { get ; set ; } public string region { get ; set ; } public object area_fias_id { get ; set ; } public object area_kladr_id { get ; set ; } public object area_with_type { get ; set ; } public object area_type { get ; set ; } public object area_type_full { get ; set ; } public object area { get ; set ; } public string city_fias_id { get ; set ; } public string city_kladr_id { get ; set ; } public string city_with_type { get ; set ; } public string city_type { get ; set ; } public string city_type_full { get ; set ; } public string city { get ; set ; } public string city_area { get ; set ; } public object city_district_fias_id { get ; set ; } public object city_district_kladr_id { get ; set ; } public string city_district_with_type { get ; set ; } public string city_district_type { get ; set ; } public string city_district_type_full { get ; set ; } public string city_district { get ; set ; } public object settlement_fias_id { get ; set ; } public object settlement_kladr_id { get ; set ; } public object settlement_with_type { get ; set ; } public object settlement_type { get ; set ; } public object settlement_type_full { get ; set ; } public object settlement { get ; set ; } public string street_fias_id { get ; set ; } public string street_kladr_id { get ; set ; } public string street_with_type { get ; set ; } public string street_type { get ; set ; } public string street_type_full { get ; set ; } public string street { get ; set ; } public string house_fias_id { get ; set ; } public string house_kladr_id { get ; set ; } public string house_type { get ; set ; } public string house_type_full { get ; set ; } public string house { get ; set ; } public object block_type { get ; set ; } public object block_type_full { get ; set ; } public object block { get ; set ; } public object flat_type { get ; set ; } public object flat_type_full { get ; set ; } public object flat { get ; set ; } public object flat_area { get ; set ; } public object square_meter_price { get ; set ; } public object flat_price { get ; set ; } public object postal_box { get ; set ; } public string fias_id { get ; set ; } public string fias_level { get ; set ; } public string kladr_id { get ; set ; } public string capital_marker { get ; set ; } public string okato { get ; set ; } public string oktmo { get ; set ; } public string tax_office { get ; set ; } public string tax_office_legal { get ; set ; } public object timezone { get ; set ; } public string geo_lat { get ; set ; } public string geo_lon { get ; set ; } public object beltway_hit { get ; set ; } public object beltway_distance { get ; set ; } public object metro { get ; set ; } public string qc_geo { get ; set ; } public object qc_complete { get ; set ; } public object qc_house { get ; set ; } public object history_values { get ; set ; } public object unparsed_parts { get ; set ; } public string source { get ; set ; } public object qc { get ; set ; } } public class Address { public string value { get ; set ; } public string unrestricted_value { get ; set ; } public Data2 data { get ; set ; } } public class Data { public string kpp { get ; set ; } public object capital { get ; set ; } public Management management { get ; set ; } public string branch_type { get ; set ; } public int branch_count { get ; set ; } public object source { get ; set ; } public object qc { get ; set ; } public string hid { get ; set ; } public string type { get ; set ; } public State state { get ; set ; } public Opf opf { get ; set ; } public Name name { get ; set ; } public string inn { get ; set ; } public string ogrn { get ; set ; } public object okpo { get ; set ; } public string okved { get ; set ; } public object okveds { get ; set ; } public object authorities { get ; set ; } public object documents { get ; set ; } public object licenses { get ; set ; } public Address address { get ; set ; } public object phones { get ; set ; } public object emails { get ; set ; } public long ogrn_date { get ; set ; } public string okved_type { get ; set ; } } public class Suggestion { public string value { get ; set ; } public string unrestricted_value { get ; set ; } public Data data { get ; set ; } } public class RootObject { public List<Suggestion> suggestions { get ; set ; } } |
Теперь мы сможем десериализовать полученный JSON:
1 | var dict = JsonConvert.DeserializeObject<RootObject>(sr.ReadToEnd()); |
Из данного объекта мы сможем получить контактный адрес контрагента:
1 2 3 4 5 6 7 8 | var address = EntityManager<EleWise.ELMA.CRM.Models.Address>.Instance.Create(); address.City = dict.suggestions[0].data.address.data.city; address.Street = dict.suggestions[0].data.address.data.street; address.Building = dict.suggestions[0].data.address.data.house; address.Save(); context.Kontragent.LegalAddress = address; context.Kontragent.PostalAddress = address; context.Kontragent.Save(); |
2. GET-запрос
Для примера воспользуемся API Google – данный сервис позволяет, например, ввести данные в произвольном виде и получить формализованное представление адреса.
Для начала работы с сервисом необходимо получить токен авторизации.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | String token = "A******************************************Y" ; //параметры запроса передаём в самом url, к которому будем обращаться var url = string .Format( "https://maps.googleapis.com/maps/api/geocode/json?address={0}&key={1}&language=ru" , context.StrokaVvodaAdresa.Replace( " " , "+" ), token); //генерация запроса HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest; req.Method = "GET" ; req.Timeout = 10000; //получение ответа var res = req.GetResponse() as HttpWebResponse; var resStream = res.GetResponseStream(); var sr = new StreamReader(resStream, Encoding.UTF8); //получаем необходимые данные //сериализация происходит так же, как в примере с post-запросом var dict = JsonConvert.DeserializeObject<RootObject>(sr.ReadToEnd()); dict.results.ForEach(i => Console.WriteLine(i.formatted_address)); |
Для реализации потребуются следующие библиотеки:
1 2 3 | using System.Net; using System.IO; using Newtonsoft.Json. |