-
Notifications
You must be signed in to change notification settings - Fork 204
/
Module.bsl
2466 lines (1920 loc) · 153 KB
/
Module.bsl
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Коннектор: удобный HTTP-клиент для 1С:Предприятие 8
//
// Copyright 2017-2019 Vladimir Bondarevskiy
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
// URL: https://github.com/vbondarevsky/Connector
// e-mail: vbondarevsky@gmail.com
// Версия: 1.3.6
//
// Требования: платформа 1С версии 8.3.10 и выше
#Область ПрограммныйИнтерфейс
#Область МетодыHTTP
#Область МетодыОбщегоНазначения
// Отправляет GET запрос
//
// Параметры:
// URL - Строка - URL ресурса, к которому будет отправлен запрос.
// ПараметрыЗапроса - Структура, Соответствие - параметры, которые будут отправлены в URL (часть после ?).
// См. описание параметра в ВызватьМетодВСеансе.
// ДополнительныеПараметры - Структура - см. описание параметра в ВызватьМетодВСеансе.
//
// Возвращаемое значение:
// Структура - ответ на выполненный запрос. См. описание возвращаемого значения в ВызватьМетодВСеансе.
//
Функция Get(URL, ПараметрыЗапроса = Неопределено, ДополнительныеПараметры = Неопределено) Экспорт
Сессия = СоздатьСессию();
ЗаполнитьДополнительныеДанные(ДополнительныеПараметры, ПараметрыЗапроса, Неопределено, Неопределено);
Возврат ВызватьМетодВСеансе(Сессия, "GET", URL, ДополнительныеПараметры);
КонецФункции
// Отправляет OPTIONS запрос
//
// Параметры:
// URL - Строка - URL ресурса, к которому будет отправлен запрос.
// ДополнительныеПараметры - Структура - см. описание параметра в ВызватьМетодВСеансе.
//
// Возвращаемое значение:
// Структура - ответ на выполненный запрос. См. описание возвращаемого значения в ВызватьМетодВСеансе.
//
Функция Options(URL, ДополнительныеПараметры = Неопределено) Экспорт
Сессия = СоздатьСессию();
ЗаполнитьДополнительныеДанные(ДополнительныеПараметры, Неопределено, Неопределено, Неопределено);
Возврат ВызватьМетодВСеансе(Сессия, "OPTIONS", URL, ДополнительныеПараметры);
КонецФункции
// Отправляет HEAD запрос
//
// Параметры:
// URL - Строка - URL ресурса, к которому будет отправлен запрос.
// ДополнительныеПараметры - Структура - см. описание параметра в ВызватьМетодВСеансе.
//
// Возвращаемое значение:
// Структура - ответ на выполненный запрос. См. описание возвращаемого значения в ВызватьМетодВСеансе.
//
Функция Head(URL, ДополнительныеПараметры = Неопределено) Экспорт
Сессия = СоздатьСессию();
ЗаполнитьДополнительныеДанные(ДополнительныеПараметры, Неопределено, Неопределено, Неопределено);
Возврат ВызватьМетодВСеансе(Сессия, "HEAD", URL, ДополнительныеПараметры);
КонецФункции
// Отправляет POST запрос
//
// Параметры:
// URL - Строка - URL ресурса, к которому будет отправлен запрос.
// Данные - Структура, Соответствие, Строка, ДвоичныеДанные - см. описание параметра в ВызватьМетодВСеансе.
// ДополнительныеПараметры - Структура - см. описание параметра в ВызватьМетодВСеансе.
//
// Возвращаемое значение:
// Структура - ответ на выполненный запрос. См. описание возвращаемого значения в ВызватьМетодВСеансе.
//
Функция Post(URL, Данные = Неопределено, ДополнительныеПараметры = Неопределено) Экспорт
Сессия = СоздатьСессию();
ЗаполнитьДополнительныеДанные(ДополнительныеПараметры, Неопределено, Данные, Неопределено);
Возврат ВызватьМетодВСеансе(Сессия, "POST", URL, ДополнительныеПараметры);
КонецФункции
// Отправляет PUT запрос
//
// Параметры:
// URL - Строка - URL ресурса, к которому будет отправлен запрос.
// Данные - Структура, Соответствие, Строка, ДвоичныеДанные - параметры, которые будут отправлены в теле запроса.
// См. описание ДополнительныеПараметры.Данные в методе ВызватьМетод.
// ДополнительныеПараметры - Структура - см. описание в методе ВызватьМетод
// Возвращаемое значение:
// Структура - ответ на выполненный запрос. См. описание в методе ВызыватьМетод
//
Функция Put(URL, Данные = Неопределено, ДополнительныеПараметры = Неопределено) Экспорт
Сессия = СоздатьСессию();
ЗаполнитьДополнительныеДанные(ДополнительныеПараметры, Неопределено, Данные, Неопределено);
Возврат ВызватьМетодВСеансе(Сессия, "PUT", URL, ДополнительныеПараметры);
КонецФункции
// Отправляет PATCH запрос
//
// Параметры:
// URL - Строка - URL ресурса, к которому будет отправлен запрос.
// Данные - Структура, Соответствие, Строка, ДвоичныеДанные - см. описание параметра в ВызватьМетодВСеансе.
// ДополнительныеПараметры - Структура - см. описание параметра в ВызватьМетодВСеансе.
//
// Возвращаемое значение:
// Структура - ответ на выполненный запрос. См. описание возвращаемого значения в ВызватьМетодВСеансе.
//
Функция Patch(URL, Данные = Неопределено, ДополнительныеПараметры = Неопределено) Экспорт
Сессия = СоздатьСессию();
ЗаполнитьДополнительныеДанные(ДополнительныеПараметры, Неопределено, Данные, Неопределено);
Возврат ВызватьМетодВСеансе(Сессия, "PATCH", URL, ДополнительныеПараметры);
КонецФункции
// Отправляет DELETE запрос
//
// Параметры:
// URL - Строка - URL ресурса, к которому будет отправлен запрос.
// Данные - Структура, Соответствие, Строка, ДвоичныеДанные - см. описание параметра в ВызватьМетодВСеансе.
// ДополнительныеПараметры - Структура - см. описание параметра в ВызватьМетодВСеансе.
//
// Возвращаемое значение:
// Структура - ответ на выполненный запрос. См. описание возвращаемого значения в ВызватьМетодВСеансе.
//
Функция Delete(URL, Данные = Неопределено, ДополнительныеПараметры = Неопределено) Экспорт
Сессия = СоздатьСессию();
ЗаполнитьДополнительныеДанные(ДополнительныеПараметры, Неопределено, Данные, Неопределено);
Возврат ВызватьМетодВСеансе(Сессия, "DELETE", URL, ДополнительныеПараметры);
КонецФункции
#КонецОбласти
#Область УпрощенныеМетодыДляРаботыСЗапросамиВФорматеJSON
// Отправляет GET запрос
//
// Параметры:
// URL - Строка - URL ресурса, к которому будет отправлен запрос.
// ПараметрыЗапроса - Структура, Соответствие - параметры, которые будут отправлены в URL (часть после ?).
// См. описание параметра в ВызватьМетодВСеансе.
// ДополнительныеПараметры - Структура - см. описание параметра в ВызватьМетодВСеансе.
// Возвращаемое значение:
// Соответствие, Структура - ответ, десериализованный из JSON.
// Параметры преобразования см. ДополнительныеПараметры.ПараметрыПреобразованияJSON
//
Функция GetJson(URL, ПараметрыЗапроса = Неопределено, ДополнительныеПараметры = Неопределено) Экспорт
Сессия = СоздатьСессию();
ЗаполнитьДополнительныеДанные(ДополнительныеПараметры, ПараметрыЗапроса, Неопределено, Неопределено);
ПараметрыПреобразованияJSON =
ВыбратьЗначение(Неопределено, ДополнительныеПараметры, "ПараметрыПреобразованияJSON", Неопределено);
Возврат КакJson(ВызватьМетодВСеансе(Сессия, "GET", URL, ДополнительныеПараметры), ПараметрыПреобразованияJSON);
КонецФункции
// Отправляет POST запрос
//
// Параметры:
// URL - Строка - URL ресурса, к которому будет отправлен запрос.
// Json - Структура, Соответствие - данные, которые необходимо сериализовать в JSON.
// ДополнительныеПараметры - Структура - см. описание параметра в ВызватьМетодВСеансе.
// Возвращаемое значение:
// Соответствие, Структура - ответ, десериализованный из JSON.
// Параметры преобразования см. ДополнительныеПараметры.ПараметрыПреобразованияJSON
//
Функция PostJson(URL, Json, ДополнительныеПараметры = Неопределено) Экспорт
Сессия = СоздатьСессию();
ЗаполнитьДополнительныеДанные(ДополнительныеПараметры, Неопределено, Неопределено, Json);
ПараметрыПреобразованияJSON =
ВыбратьЗначение(Неопределено, ДополнительныеПараметры, "ПараметрыПреобразованияJSON", Неопределено);
Возврат КакJson(ВызватьМетодВСеансе(Сессия, "POST", URL, ДополнительныеПараметры), ПараметрыПреобразованияJSON);
КонецФункции
// Отправляет PUT запрос
//
// Параметры:
// URL - Строка - URL ресурса, к которому будет отправлен запрос.
// Json - Структура, Соответствие - данные, которые необходимо сериализовать в JSON.
// ДополнительныеПараметры - Структура - см. описание параметра в ВызватьМетодВСеансе.
// Возвращаемое значение:
// Соответствие, Структура - ответ, десериализованный из JSON.
// Параметры преобразования см. ДополнительныеПараметры.ПараметрыПреобразованияJSON
//
Функция PutJson(URL, Json, ДополнительныеПараметры = Неопределено) Экспорт
Сессия = СоздатьСессию();
ЗаполнитьДополнительныеДанные(ДополнительныеПараметры, Неопределено, Неопределено, Json);
ПараметрыПреобразованияJSON =
ВыбратьЗначение(Неопределено, ДополнительныеПараметры, "ПараметрыПреобразованияJSON", Неопределено);
Возврат КакJson(ВызватьМетодВСеансе(Сессия, "PUT", URL, ДополнительныеПараметры), ПараметрыПреобразованияJSON);
КонецФункции
// Отправляет DELETE запрос
//
// Параметры:
// URL - Строка - URL ресурса, к которому будет отправлен запрос.
// Json - Структура, Соответствие - данные, которые необходимо сериализовать в JSON.
// ДополнительныеПараметры - Структура - см. описание параметра в ВызватьМетодВСеансе.
// Возвращаемое значение:
// Соответствие, Структура - ответ, десериализованный из JSON.
// Параметры преобразования см. ДополнительныеПараметры.ПараметрыПреобразованияJSON
//
Функция DeleteJson(URL, Json, ДополнительныеПараметры = Неопределено) Экспорт
Сессия = СоздатьСессию();
ЗаполнитьДополнительныеДанные(ДополнительныеПараметры, Неопределено, Неопределено, Json);
ПараметрыПреобразованияJSON =
ВыбратьЗначение(Неопределено, ДополнительныеПараметры, "ПараметрыПреобразованияJSON", Неопределено);
Возврат КакJson(ВызватьМетодВСеансе(Сессия, "DELETE", URL, ДополнительныеПараметры), ПараметрыПреобразованияJSON);
КонецФункции
#КонецОбласти
// Отправляет данные на указанный адрес для обработки с использованием указанного HTTP-метода.
//
// Параметры:
// Метод - Строка - имя HTTP-метода для запроса.
// URL - Строка - URL ресурса, к которому будет отправлен запрос.
// ДополнительныеПараметры - Структура - см. описание параметра в ВызватьМетодВСеансе.
//
// Возвращаемое значение:
// Структура - ответ на выполненный запрос. См. описание возвращаемого значения в ВызватьМетодВСеансе.
//
Функция ВызватьМетод(Метод, URL, ДополнительныеПараметры = Неопределено) Экспорт
Сессия = СоздатьСессию();
ЗаполнитьДополнительныеДанные(ДополнительныеПараметры, Неопределено, Неопределено, Неопределено);
Возврат ВызватьМетодВСеансе(Сессия, Метод, URL, ДополнительныеПараметры);
КонецФункции
#КонецОбласти
#Область ФорматыОтветов
// Возвращает ответ сервера в виде десериализованного значения JSON.
//
// Параметры:
// Ответ - Структура - ответ сервера на отправленный запрос.
// См. описание возвращаемого значения ВызватьМетод.
// ПараметрыПреобразованияJSON - Структура - задает параметры преобразования JSON.
// *ПрочитатьВСоответствие - Булево - Если Истина, чтение объекта JSON будет выполнено в Соответствие.
// Если Ложь, объекты будут считываться в объект типа Структура.
// *ФорматДатыJSON - ФорматДатыJSON - формат, в котором представлена дата в строке, подлежащей преобразованию.
// *ИменаСвойствСоЗначениямиДата - Массив, Строка - имена свойств JSON,
// для которых нужно вызывать восстановление даты из строки.
//
// Возвращаемое значение:
// Соответствие - ответ сервера в виде десериализованного значения JSON.
// Если ПараметрыПреобразования.ПрочитатьВСоответствие = Истина (по умолчанию).
// Структура - если ПараметрыПреобразования.ПрочитатьВСоответствие = Ложь.
//
Функция КакJson(Ответ, ПараметрыПреобразованияJSON = Неопределено) Экспорт
Возврат JsonВОбъект(РаспаковатьОтвет(Ответ), Ответ.Кодировка, ПараметрыПреобразованияJSON);
КонецФункции
// Возвращает ответ сервера в виде текста.
//
// Параметры:
// Ответ - Структура - ответ сервера на отправленный запрос.
// См. описание возвращаемого значения ВызватьМетод.
// Кодировка - Строка, КодировкаТекста - определяет кодировку текста.
// Если значение не задано, то кодировка извлекается из Ответ.Кодировка.
//
// Возвращаемое значение:
// Строка - ответ сервера в виде текста.
//
Функция КакТекст(Ответ, Кодировка = Неопределено) Экспорт
Если Не ЗначениеЗаполнено(Кодировка) Тогда
Кодировка = Ответ.Кодировка;
КонецЕсли;
ЧтениеТекста = Новый ЧтениеТекста(РаспаковатьОтвет(Ответ).ОткрытьПотокДляЧтения(), Кодировка);
Текст = ЧтениеТекста.Прочитать();
ЧтениеТекста.Закрыть();
Возврат Текст;
КонецФункции
// Возвращает ответ сервера в двоичных данных.
//
// Параметры:
// Ответ - Структура - ответ сервера на отправленный запрос.
// См. описание возвращаемого значения ВызватьМетод.
//
// Возвращаемое значение:
// Строка - ответ сервера в виде двоичных данных.
//
Функция КакДвоичныеДанные(Ответ) Экспорт
Возврат РаспаковатьОтвет(Ответ);
КонецФункции
#КонецОбласти
#Область Сессия
// Создает объект для хранения параметров сессии.
//
// Возвращаемое значение:
// Структура - параметры сессии:
// *Заголовки - Соответствие - HTTP заголовки запроса.
// *Аутентификация - Структура - параметры аутентификации запроса.
// *Тип - Строка - тип аутентификации. Допустимые значения: Digest, Basic. Для Basic Тип можно не указывать.
// *Пользователь - Строка - имя пользователя.
// *Пароль - Строка - пароль пользователя.
// *Прокси - ИнтернетПрокси - параметры прокси, которые будут использованы при отправке запроса.
// Значение по умолчанию: Неопределено. При этом если в конфигурации используется БСП,
// то значения прокси будет взято из БСП.
// *ПараметрыЗапроса - Структура, Соответствие - параметры, которые будут отправлены в URL (часть после ?):
// *<Ключ> - Строка - ключ параметра в URL.
// *<Значение> - Строка - значение параметра URL
// - Массив - сформирует строку из нескольких параметров: key=value1&key=value2 и т.д.
// *ПроверятьSSL - Булево - Ложь - проверка сертификата сервера не выполняется.
// - Истина - используется значение СертификатыУдостоверяющихЦентровОС.
// - СертификатыУдостоверяющихЦентровФайл - см. в синтаксис-помощнике описание
// СертификатыУдостоверяющихЦентровФайл.
// Значение по умолчанию: Истина.
// *КлиентскийСертификатSSL - СертификатКлиентаФайл - см. в синтаксис-помощнике описание СертификатКлиентаФайл.
// - СертификатКлиентаWindows - см. в синтаксис-помощнике описание
// СертификатКлиентаWindows.
// Значение по умолчанию: Неопределено.
// *МаксимальноеКоличествоПеренаправлений - Число - максимальное количество редиректов. Защита от зацикливания.
// Значение по умолчанию:
// см. функцию МаксимальноеКоличествоПеренаправлений
// *Cookies - Соответствие - хранилище cookies.
//
Функция СоздатьСессию() Экспорт
Сессия = Новый Структура;
Сессия.Вставить("Заголовки", ЗаголовкиПоУмолчанию());
Сессия.Вставить("Аутентификация", Неопределено);
Сессия.Вставить("Прокси", Неопределено);
Сессия.Вставить("ПараметрыЗапроса", Новый Структура);
Сессия.Вставить("ПроверятьSSL", Истина);
Сессия.Вставить("КлиентскийСертификатSSL", Неопределено);
Сессия.Вставить("МаксимальноеКоличествоПеренаправлений", МаксимальноеКоличествоПеренаправлений());
Сессия.Вставить("Cookies", Новый Соответствие);
Сессия.Вставить("СлужебныеДанные", Новый Структура("ПараметрыDigest"));
Возврат Сессия;
КонецФункции
// Отправляет данные на указанный адрес для обработки с использованием указанного HTTP-метода в контексте Сессии.
//
// Параметры:
// Сессия - Структура - параметры сессии:
// *Заголовки - Соответствие - HTTP заголовки запроса.
// *Аутентификация - Структура - параметры аутентификации запроса.
// *ИспользоватьАутентификациюОС - Булево - включает использование аутентификации NTLM или Negotiate.
// Значение по умолчанию: Ложь.
// *Тип - Строка - тип аутентификации. Для Basic Тип можно не указывать.
// Если Тип = Digest или Basic:
// *Пользователь - Строка - имя пользователя.
// *Пароль - Строка - пароль пользователя.
// Если Тип = AWS4-HMAC-SHA256:
// *ИдентификаторКлючаДоступа - Строка - идентификатор ключа доступа.
// *СекретныйКлюч - Строка - секретный ключ.
// *Сервис - Строка - сервис, к которому выполняется подключение.
// *Регион - Строка - регион, к которому выполняется подключение.
// *Прокси - ИнтернетПрокси - параметры прокси, которые будут использованы при отправке запроса.
// Значение по умолчанию: Неопределено. При этом если в конфигурации используется БСП,
// то значения прокси будет взято из БСП.
// *ПараметрыЗапроса - Структура, Соответствие - параметры, которые будут отправлены в URL (часть после ?):
// *<Ключ> - Строка - ключ параметра в URL.
// *<Значение> - Строка - значение параметра URL
// - Массив - сформирует строку из нескольких параметров: key=value1&key=value2 и т.д.
// *ПроверятьSSL - Булево - Ложь - проверка сертификата сервера не выполняется.
// - Истина - используется значение СертификатыУдостоверяющихЦентровОС.
// - СертификатыУдостоверяющихЦентровФайл - см. в синтаксис-помощнике описание
// СертификатыУдостоверяющихЦентровФайл.
// Значение по умолчанию: Истина.
// *КлиентскийСертификатSSL - СертификатКлиентаФайл - см. в синтаксис-помощнике описание СертификатКлиентаФайл.
// - СертификатКлиентаWindows - см. в синтаксис-помощнике описание
// СертификатКлиентаWindows.
// Значение по умолчанию: Неопределено.
// *МаксимальноеКоличествоПеренаправлений - Число - максимальное количество редиректов. Защита от зацикливания.
// Значение по умолчанию:
// см. функцию МаксимальноеКоличествоПеренаправлений
// *Cookies - Соответствие - хранилище cookies.
// Метод - Строка - имя HTTP-метода для запроса.
// URL - Строка - URL ресурса, к которому будет отправлен запрос.
// ДополнительныеПараметры - Структура - позволяет задать дополнительные параметры:
// *Заголовки - Соответствие - см. описание Сессия.Заголовки.
// *Аутентификация - Структура - см. описание Сессия.Аутентификация
// *Прокси - ИнтернетПрокси - см. описание Сессия.Прокси.
// *ПараметрыЗапроса - Структура, Соответствие - см. описание Сессия.ПараметрыЗапроса.
// *ПроверятьSSL - Булево - см. описание Сессия.ПроверятьSSL.
// *КлиентскийСертификатSSL - см. описание Сессия.КлиентскийСертификатSSL.
// *Cookies - Массив - см. описание Сессия.Cookies.
// *Таймаут - Число - время ожидания осуществляемого соединения и операций, в секундах.
// Значение по умолчанию - 30 сек.
// *РазрешитьПеренаправление - Булево - Истина - редиректы будут автоматически разрешены.
// Ложь - будет выполнен только один запрос к серверу.
// *Json - Структура, Соответствие - данные, которые необходимо сериализовать в JSON.
// *ПараметрыПреобразованияJSON - Структура - задает параметры преобразования JSON:
// **ПрочитатьВСоответствие - Булево - Если Истина, чтение объекта JSON будет выполнено в Соответствие.
// Если Ложь, объекты будут считываться в объект типа Структура.
// **ФорматДатыJSON - ФорматДатыJSON - формат, в котором представлена дата в строке,
// подлежащей преобразованию.
// **ИменаСвойствСоЗначениямиДата - Массив, Строка - имена свойств JSON,
// для которых нужно вызывать восстановление даты из строки.
// *ПараметрыЗаписиJSON - Структура - параметры, используемые при записи объекта JSON.
// См. в синтаксис-помощнике описание ПараметрыЗаписиJSON.
// *Данные - Структура, Соответствие - поля формы, которые необходимо отправить в запрос:
// *<Ключ> - Строка - имя поля.
// *<Значение> - Строка - значение поля.
// - Строка, ДвоичныеДанные - произвольные данные, которые необходимо отправить в запросе.
// *Файлы - Структура, Массив - файлы, которые необходимо отправить в запросе:
// *Имя - Строка - имя поля формы.
// *Данные - ДвоичныеДанные - двоичные данные файла.
// *ИмяФайла - Строка - имя файла.
// *Тип - Строка - MIME-тип файла.
// *Заголовки - Соответствие, Неопределено - HTTP заголовки запроса.
//
// Возвращаемое значение:
// Структура - ответ на выполненный запрос:
// *ВремяВыполнения - Число - время выполнения запроса в миллисекундах.
// *Cookies - Соответствие - cookies полученные с сервера.
// *Заголовки - Соответствие - HTTP заголовки ответа.
// *ЭтоПостоянныйРедирект - Булево - признак постоянного редиректа.
// *ЭтоРедирект - Булево - признак редиректа.
// *Кодировка - Строка - кодировка текста ответа.
// *Тело - ДвоичныеДанные - тело ответа.
// *КодСостояния - Число - код состояния ответа.
// *URL - Строка - итоговый URL, по которому был выполнен запрос.
//
Функция ВызватьМетодВСеансе(Сессия, Метод, URL, ДополнительныеПараметры = Неопределено) Экспорт
ЗаполнитьДополнительныеДанные(ДополнительныеПараметры, Неопределено, Неопределено, Неопределено);
Возврат ВызватьHTTPМетод(Сессия, Метод, URL, ДополнительныеПараметры);
КонецФункции
#КонецОбласти
#Область ВспомогательныеФункции
// Возвращает структурированное представление URL.
//
// Параметры:
// URL - Строка - URL ресурса, к которому будет отправлен запрос.
//
// Возвращаемое значение:
// Структура - структура URL:
// *Схема - Строка - схема обращения к серверу (http, https).
// *Аутентификация - Структура - параметры аутентификации:
// *Пользователь - Строка - имя пользователя.
// *Пароль - Строка - пароль пользователя.
// *Сервер - Строка - адрес сервера.
// *Порт - Число - порт сервера.
// *Путь - Строка - адрес ресурса на сервере.
// *ПараметрыЗапроса - Соответствие - параметры запроса передаваемые на сервер в URL (часть после ?):
// *<Ключ> - Строка - ключ параметра в URL.
// *<Значение> - Строка - значение параметра URL;
// - Массив - значения параметра (key=value1&key=value2).
// *Фрагмент - Строка - часть URL после #.
//
Функция РазобратьURL(Знач URL) Экспорт
Схема = "";
Путь = "";
Аутентификация = Новый Структура("Пользователь, Пароль", "", "");
Сервер = "";
Порт = "";
Фрагмент = "";
ДопустимыеСхемы = СтрРазделить("http,https", ",");
URLБезСхемы = URL;
РазбитьСтрокуПоРазделителю(Схема, URLБезСхемы, "://");
Если ДопустимыеСхемы.Найти(НРег(Схема)) <> Неопределено Тогда
URL = URLБезСхемы;
Иначе
Схема = "";
КонецЕсли;
Результат = РазделитьПоПервомуНайденномуРазделителю(URL, СтрРазделить("/,?,#", ","));
URL = Результат[0];
Если ЗначениеЗаполнено(Результат[2]) Тогда
Путь = Результат[2] + Результат[1];
КонецЕсли;
АутентификацияСтрока = "";
РазбитьСтрокуПоРазделителю(АутентификацияСтрока, URL, "@");
Если ЗначениеЗаполнено(АутентификацияСтрока) Тогда
АутентификацияЧасти = СтрРазделить(АутентификацияСтрока, ":");
Аутентификация.Пользователь = АутентификацияЧасти[0];
Аутентификация.Пароль = АутентификацияЧасти[1];
КонецЕсли;
// IPv6
РазбитьСтрокуПоРазделителю(Сервер, URL, "]");
Если ЗначениеЗаполнено(Сервер) Тогда
Сервер = Сервер + "]";
КонецЕсли;
URL = СтрЗаменить(URL, "/", "");
РазбитьСтрокуПоРазделителю(Порт, URL, ":", Истина);
Если Не ЗначениеЗаполнено(Сервер) Тогда
Сервер = URL;
КонецЕсли;
Если ЗначениеЗаполнено(Порт) Тогда
Порт = Число(Порт);
Иначе
Порт = 0;
КонецЕсли;
РазбитьСтрокуПоРазделителю(Фрагмент, Путь, "#", Истина);
ПараметрыЗапроса = ЗаполнитьПараметрыЗапроса(Путь);
Если Не ЗначениеЗаполнено(Схема) Тогда
Схема = "http";
КонецЕсли;
Путь = ?(ЗначениеЗаполнено(Путь), Путь, "/");
Результат = Новый Структура;
Результат.Вставить("Схема", Схема);
Результат.Вставить("Аутентификация", Аутентификация);
Результат.Вставить("Сервер", Сервер);
Результат.Вставить("Порт", Порт);
Результат.Вставить("Путь", Путь);
Результат.Вставить("ПараметрыЗапроса", ПараметрыЗапроса);
Результат.Вставить("Фрагмент", Фрагмент);
Возврат Результат;
КонецФункции
// Преобразование Объекта в JSON.
//
// Параметры:
// Объект - Произвольный - данные, которые необходимо преобразовать в JSON.
// ПараметрыПреобразования - Структура - кодировка текста JSON. Значение по умолчанию - utf-8.
// *ФорматДатыJSON - ФорматДатыJSON - определяет формат сериализации дат JSON-объектов.
// ПараметрыЗаписи - Структура - параметры преобразования JSON:
// *ПереносСтрок - ПереносСтрокJSON - определяет способ переноса строк,
// который будет использован при записи данных JSON.
// *СимволыОтступа - Строка - определяет символы отступа, используемые при записи данных JSON.
// *ИспользоватьДвойныеКавычки - Булево - определяет, будут ли при записи имена свойств JSON
// записываться в двойных кавычках.
// *ЭкранированиеСимволов - ЭкранированиеСимволовJSON - определяет используемый способ экранирования (замены)
// символов при записи данных JSON.
// *ЭкранироватьУгловыеСкобки - Булево - определяет, будут ли при записи экранироваться символы "<" и ">".
// *ЭкранироватьРазделителиСтрок - Булево - определяет, будут ли экранироваться разделители строк
// U+2028 (line-separator) и U+2029 (page-separator).
// *ЭкранироватьАмперсанд - Булево - определяет, будет ли при записи экранироваться символ амперсанда "&".
// *ЭкранироватьОдинарныеКавычки - Булево - определяет, будут ли экранироваться одинарные кавычки.
// *ЭкранироватьСлеш - Булево - определяет, будет ли экранироваться слеш (косая черта) при записи значения.
//
// Возвращаемое значение:
// Строка - объект в формате JSON.
//
Функция ОбъектВJson(Объект, Знач ПараметрыПреобразования = Неопределено, Знач ПараметрыЗаписи = Неопределено) Экспорт
ПараметрыПреобразованияJSON = ДополнитьПараметрыПреобразованияJSON(ПараметрыПреобразования);
НастройкиСериализации = Новый НастройкиСериализацииJSON;
НастройкиСериализации.ФорматСериализацииДаты = ПараметрыПреобразованияJSON.ФорматДатыJSON;
ПараметрыЗаписи = ДополнитьПараметрыЗаписиJSON(ПараметрыЗаписи);
ПараметрыЗаписиJSON = Новый ПараметрыЗаписиJSON(
ПараметрыЗаписи.ПереносСтрок,
ПараметрыЗаписи.СимволыОтступа,
ПараметрыЗаписи.ИспользоватьДвойныеКавычки,
ПараметрыЗаписи.ЭкранированиеСимволов,
ПараметрыЗаписи.ЭкранироватьУгловыеСкобки,
ПараметрыЗаписи.ЭкранироватьРазделителиСтрок,
ПараметрыЗаписи.ЭкранироватьАмперсанд,
ПараметрыЗаписи.ЭкранироватьОдинарныеКавычки,
ПараметрыЗаписи.ЭкранироватьСлеш);
ЗаписьJSON = Новый ЗаписьJSON;
ЗаписьJSON.УстановитьСтроку(ПараметрыЗаписиJSON);
ЗаписатьJSON(ЗаписьJSON, Объект, НастройкиСериализации);
Возврат ЗаписьJSON.Закрыть();
КонецФункции
// Преобразование JSON в Объект.
//
// Параметры:
// Json - Поток, ДвоичныеДанные - данные в формате JSON.
// Кодировка - Строка - кодировка текста JSON. Значение по умолчанию - utf-8.
// ПараметрыПреобразования - Структура - параметры преобразования JSON:
// *ПрочитатьВСоответствие - Булево - если Истина, чтение объекта JSON будет выполнено в Соответствие,
// иначе в Структура.
// *ИменаСвойствСоЗначениямиДата - Массив, Строка, ФиксированныйМассив - имена свойств JSON,
// для которых нужно вызывать восстановление даты из строки.
// *ФорматДатыJSON - ФорматДатыJSON - определяет формат десериализации дат JSON-объектов.
//
// Возвращаемое значение:
// Произвольный - значение, десериализованное из JSON.
//
Функция JsonВОбъект(Json, Кодировка = "utf-8", ПараметрыПреобразования = Неопределено) Экспорт
ПараметрыПреобразованияJSON = ДополнитьПараметрыПреобразованияJSON(ПараметрыПреобразования);
ЧтениеJSON = Новый ЧтениеJSON;
Если ТипЗнч(Json) = Тип("ДвоичныеДанные") Тогда
ЧтениеJSON.ОткрытьПоток(Json.ОткрытьПотокДляЧтения(), Кодировка);
Иначе
ЧтениеJSON.ОткрытьПоток(Json, Кодировка);
КонецЕсли;
Объект = ПрочитатьJSON(
ЧтениеJSON,
ПараметрыПреобразованияJSON.ПрочитатьВСоответствие,
ПараметрыПреобразованияJSON.ИменаСвойствСоЗначениямиДата,
ПараметрыПреобразованияJSON.ФорматДатыJSON);
ЧтениеJSON.Закрыть();
Возврат Объект;
КонецФункции
// Вычисляет HMAC (hash-based message authentication code).
//
// Параметры:
// Ключ - ДвоичныеДанные - секретный ключ.
// Данные - ДвоичныеДанные - данные, для которых нужно посчитать HMAC.
// Алгоритм - ХешФункция - алгоритм, используемый для вычисления хеша.
//
// Возвращаемое значение:
// ДвоичныеДанные - вычисленное значение HMAC.
//
Функция HMAC(Ключ, Данные, Алгоритм) Экспорт
ДлинаБлока = 64;
Если Ключ.Размер() > ДлинаБлока Тогда
Хеширование = Новый ХешированиеДанных(Алгоритм);
Хеширование.Добавить(Ключ);
КлючБуфер = ПолучитьБуферДвоичныхДанныхИзДвоичныхДанных(Хеширование.ХешСумма);
Иначе
КлючБуфер = ПолучитьБуферДвоичныхДанныхИзДвоичныхДанных(Ключ);
КонецЕсли;
ИзмененныйКлюч = Новый БуферДвоичныхДанных(ДлинаБлока);
ИзмененныйКлюч.Записать(0, КлючБуфер);
ВнутреннийКлюч = ИзмененныйКлюч.Скопировать();
ВнешнийКлюч = ИзмененныйКлюч;
ВнутреннееВыравнивание = Новый БуферДвоичныхДанных(ДлинаБлока);
ВнешнееВыравнивание = Новый БуферДвоичныхДанных(ДлинаБлока);
Для Индекс = 0 По ДлинаБлока - 1 Цикл
ВнутреннееВыравнивание.Установить(Индекс, 54);
ВнешнееВыравнивание.Установить(Индекс, 92);
КонецЦикла;
ВнутреннееХеширование = Новый ХешированиеДанных(Алгоритм);
ВнешнееХеширование = Новый ХешированиеДанных(Алгоритм);
ВнутреннийКлюч.ЗаписатьПобитовоеИсключительноеИли(0, ВнутреннееВыравнивание);
ВнешнийКлюч.ЗаписатьПобитовоеИсключительноеИли(0, ВнешнееВыравнивание);
ВнешнееХеширование.Добавить(ПолучитьДвоичныеДанныеИзБуфераДвоичныхДанных(ВнешнийКлюч));
ВнутреннееХеширование.Добавить(ПолучитьДвоичныеДанныеИзБуфераДвоичныхДанных(ВнутреннийКлюч));
Если ЗначениеЗаполнено(Данные) Тогда
ВнутреннееХеширование.Добавить(Данные);
КонецЕсли;
ВнешнееХеширование.Добавить(ВнутреннееХеширование.ХешСумма);
Возврат ВнешнееХеширование.ХешСумма;
КонецФункции
Функция КодыСостоянияHTTP() Экспорт
КодыСостояния = Новый Структура;
КодыСостояния.Вставить("ПеремещеноНавсегда_301", 301);
КодыСостояния.Вставить("ПеремещеноВременно_302", 302);
КодыСостояния.Вставить("СмотретьДругое_303", 303);
КодыСостояния.Вставить("ВременноеПеренаправление_307", 307);
КодыСостояния.Вставить("ПостоянноеПеренаправление_308", 308);
КодыСостояния.Вставить("НеверныйЗапрос_400", 400);
КодыСостояния.Вставить("ВнутренняяОшибкаСервера_500", 500);
Возврат КодыСостояния;
КонецФункции
#КонецОбласти
#КонецОбласти
#Область СлужебныеПроцедурыИФункции
Функция ВызватьHTTPМетод(Сессия, Метод, URL, ДополнительныеПараметры)
КодыСостоянияHTTP = КоннекторHTTP.КодыСостоянияHTTP();
ПодготовленныйЗапрос = ПодготовитьЗапрос(Сессия, Метод, URL, ДополнительныеПараметры);
НастройкиПодключения = ПолучитьНастройкиПодключения(Метод, URL, ДополнительныеПараметры);
Ответ = ОтправитьЗапрос(Сессия, ПодготовленныйЗапрос, НастройкиПодключения);
Перенаправление = 0;
Пока Перенаправление < Сессия.МаксимальноеКоличествоПеренаправлений Цикл
Если Не НастройкиПодключения.РазрешитьПеренаправление ИЛИ Не Ответ.ЭтоРедирект Тогда
Возврат Ответ;
КонецЕсли;
НовыйURL = СформироватьНовыйURLПриПеренаправлении(Ответ);
ПодготовленныйЗапрос.URL = КодироватьСтроку(НовыйURL, СпособКодированияСтроки.URLВКодировкеURL);
НовыйHTTPЗапрос = Новый HTTPЗапрос(СобратьАдресРесурса(КоннекторHTTP.РазобратьURL(НовыйURL), Неопределено));
ПереопределитьМетод(ПодготовленныйЗапрос, Ответ);
Если Ответ.КодСостояния <> КодыСостоянияHTTP.ВременноеПеренаправление_307
И Ответ.КодСостояния <> КодыСостоянияHTTP.ПостоянноеПеренаправление_308 Тогда
УдалитьЗаголовки(ПодготовленныйЗапрос.Заголовки, "content-length,content-type,transfer-encoding");
НовыйHTTPЗапрос.Заголовки = ПодготовленныйЗапрос.Заголовки;
Иначе
ИсходныйПоток = ПодготовленныйЗапрос.HTTPЗапрос.ПолучитьТелоКакПоток();
ИсходныйПоток.КопироватьВ(НовыйHTTPЗапрос.ПолучитьТелоКакПоток());
КонецЕсли;
ПодготовленныйЗапрос.HTTPЗапрос = НовыйHTTPЗапрос;
УдалитьЗаголовки(ПодготовленныйЗапрос.Заголовки, "cookies");
ПодготовленныйЗапрос.Cookies = ОбъединитьCookies(Сессия.Cookies, ПодготовленныйЗапрос.Cookies);
ПодготовитьCookies(ПодготовленныйЗапрос);
// INFO: по хорошему аутентификацию нужно привести к новых параметрам, но пока будем игнорировать.
Ответ = ОтправитьЗапрос(Сессия, ПодготовленныйЗапрос, НастройкиПодключения);
Перенаправление = Перенаправление + 1;
КонецЦикла;
ВызватьИсключение("СлишкомМногоПеренаправлений");
КонецФункции
Функция СформироватьНовыйURLПриПеренаправлении(Ответ)
НовыйURL = ПолучитьЗначениеЗаголовка("location", Ответ.Заголовки);
НовыйURL = РаскодироватьСтроку(НовыйURL, СпособКодированияСтроки.URLВКодировкеURL);
// Редирект без схемы
Если СтрНачинаетсяС(НовыйURL, "//") Тогда
СтруктураURL = КоннекторHTTP.РазобратьURL(Ответ.URL);
НовыйURL = СтруктураURL.Схема + ":" + НовыйURL;
КонецЕсли;
СтруктураURL = КоннекторHTTP.РазобратьURL(НовыйURL);
Если Не ЗначениеЗаполнено(СтруктураURL.Сервер) Тогда
СтруктураURLОтвета = КоннекторHTTP.РазобратьURL(Ответ.URL);
БазовыйURL = СтрШаблон("%1://%2", СтруктураURLОтвета.Схема, СтруктураURLОтвета.Сервер);
Если ЗначениеЗаполнено(СтруктураURLОтвета.Порт) Тогда
БазовыйURL = БазовыйURL + Формат(СтруктураURLОтвета.Порт, "ЧРГ=; ЧГ=");
КонецЕсли;
НовыйURL = БазовыйURL + НовыйURL;
КонецЕсли;
Возврат НовыйURL;
КонецФункции
Процедура УдалитьЗаголовки(Заголовки, СписокЗаголовковСтрокой)
ЗаголовкиДляУдаления = Новый Массив;
СписокЗаголовков = СтрРазделить(СписокЗаголовковСтрокой, ",", Ложь);
Для Каждого Заголовок Из Заголовки Цикл
Если СписокЗаголовков.Найти(НРег(Заголовок.Ключ)) <> Неопределено Тогда
ЗаголовкиДляУдаления.Добавить(Заголовок.Ключ);
КонецЕсли;
КонецЦикла;
Для Каждого ЗаголовокДляУдаления Из ЗаголовкиДляУдаления Цикл
Заголовки.Удалить(ЗаголовокДляУдаления);
КонецЦикла;
КонецПроцедуры
Функция ПолучитьНастройкиПодключения(Метод, URL, ДополнительныеПараметры)
РазрешитьПеренаправление =
ПолучитьЗначениеПоКлючу(ДополнительныеПараметры, "РазрешитьПеренаправление", ВРег(Метод) <> "HEAD");
ПроверятьSSL = ПолучитьЗначениеПоКлючу(ДополнительныеПараметры, "ПроверятьSSL", Истина);
КлиентскийСертификатSSL = ПолучитьЗначениеПоКлючу(ДополнительныеПараметры, "КлиентскийСертификатSSL");
Прокси = ПолучитьЗначениеПоКлючу(ДополнительныеПараметры, "Прокси", ПолучитьПроксиПоУмолчанию(URL));
Настройки = Новый Структура;
Настройки.Вставить("Таймаут", ПолучитьТаймаут(ДополнительныеПараметры));
Настройки.Вставить("РазрешитьПеренаправление", РазрешитьПеренаправление);
Настройки.Вставить("ПроверятьSSL", ПроверятьSSL);
Настройки.Вставить("КлиентскийСертификатSSL", КлиентскийСертификатSSL);
Настройки.Вставить("Прокси", Прокси);
Возврат Настройки;
КонецФункции
Функция ПолучитьТаймаут(ДополнительныеПараметры)
Если ДополнительныеПараметры.Свойство("Таймаут") И ЗначениеЗаполнено(ДополнительныеПараметры.Таймаут) Тогда
Таймаут = ДополнительныеПараметры.Таймаут;
Иначе
Таймаут = СтандартныйТаймаут();
КонецЕсли;
Возврат Таймаут;
КонецФункции
Функция ПолучитьПроксиПоУмолчанию(URL)
ПроксиПоУмолчанию = Новый ИнтернетПрокси;
Если Метаданные.ОбщиеМодули.Найти("ПолучениеФайловИзИнтернетаКлиентСервер") = Неопределено Тогда
ПолучениеФайловИзИнтернетаКлиентСервер = Неопределено;
Иначе
СтруктураURL = РазобратьURL(URL);
ПроксиПоУмолчанию = ПолучениеФайловИзИнтернетаКлиентСервер.ПолучитьПрокси(СтруктураURL.Схема);
КонецЕсли;
Возврат ПроксиПоУмолчанию;
КонецФункции
Функция ПодготовитьЗапрос(Сессия, Метод, URL, ДополнительныеПараметры)
Cookies = ВыбратьЗначение(Неопределено, ДополнительныеПараметры, "Cookies", Новый Массив);
Cookies = ОбъединитьCookies(ДозаполнитьCookie(Сессия.Cookies, URL), ДозаполнитьCookie(Cookies, URL));
Аутентификация = ОбъединитьПараметрыАутентификации(
ВыбратьЗначение(Неопределено, ДополнительныеПараметры, "Аутентификация", Новый Структура),
Сессия.Аутентификация);
ПараметрыЗапроса = ОбъединитьПараметрыЗапроса(
ВыбратьЗначение(Неопределено, ДополнительныеПараметры, "ПараметрыЗапроса", Новый Структура),
Сессия.ПараметрыЗапроса);
Заголовки = ОбъединитьЗаголовки(
ВыбратьЗначение(Неопределено, ДополнительныеПараметры, "Заголовки", Новый Соответствие),
Сессия.Заголовки);
ПараметрыПреобразованияJSON =
ВыбратьЗначение(Неопределено, ДополнительныеПараметры, "ПараметрыПреобразованияJSON", Неопределено);
ПодготовленныйЗапрос = Новый Структура;
ПодготовленныйЗапрос.Вставить("Cookies", Cookies);
ПодготовленныйЗапрос.Вставить("Аутентификация", Аутентификация);
ПодготовленныйЗапрос.Вставить("Метод", Метод);
ПодготовленныйЗапрос.Вставить("Заголовки", Заголовки);
ПодготовленныйЗапрос.Вставить("ПараметрыЗапроса", ПараметрыЗапроса);
ПодготовленныйЗапрос.Вставить("URL", ПодготовитьURL(URL, ПараметрыЗапроса));
ПодготовленныйЗапрос.Вставить("ПараметрыПреобразованияJSON", ПараметрыПреобразованияJSON);
ПодготовитьCookies(ПодготовленныйЗапрос);
ПодготовитьТелоЗапроса(
ПодготовленныйЗапрос,
ВыбратьЗначение(Неопределено, ДополнительныеПараметры, "Данные", Новый Структура),
ВыбратьЗначение(Неопределено, ДополнительныеПараметры, "Файлы", Новый Массив),
ВыбратьЗначение(Неопределено, ДополнительныеПараметры, "Json", Неопределено),
ВыбратьЗначение(Неопределено, ДополнительныеПараметры, "ПараметрыЗаписиJSON", Неопределено));
ПодготовитьАутентификацию(ПодготовленныйЗапрос);
Возврат ПодготовленныйЗапрос;
КонецФункции
Функция ДозаполнитьCookie(Cookies, URL)
СтруктураURL = РазобратьURL(URL);
НовыеCookies = Новый Массив;
Если ТипЗнч(Cookies) = Тип("Массив") Тогда
Для Каждого Cookie Из Cookies Цикл
НовыйCookie = КонструкторCookie(Cookie.Наименование, Cookie.Значение);
ЗаполнитьЗначенияСвойств(НовыйCookie, Cookie);
Если Не ЗначениеЗаполнено(НовыйCookie.Домен) Тогда
НовыйCookie.Домен = СтруктураURL.Сервер;
КонецЕсли;
Если Не ЗначениеЗаполнено(НовыйCookie.Путь) Тогда
НовыйCookie.Путь = "/";
КонецЕсли;
НовыеCookies.Добавить(НовыйCookie);
КонецЦикла;
Возврат НовыеCookies;
КонецЕсли;
Возврат Cookies;
КонецФункции
Процедура УдалитьCookieИзХранилища(ХранилищеCookies, Cookie)
Если ХранилищеCookies.Получить(Cookie.Домен) <> Неопределено
И ХранилищеCookies[Cookie.Домен].Получить(Cookie.Путь) <> Неопределено
И ХранилищеCookies[Cookie.Домен][Cookie.Путь].Получить(Cookie.Наименование) <> Неопределено Тогда
ХранилищеCookies[Cookie.Домен][Cookie.Путь].Удалить(Cookie.Наименование);
КонецЕсли;
КонецПроцедуры
Процедура ДобавитьCookieВХранилище(ХранилищеCookies, Cookie, Замещать = Ложь)
Если ХранилищеCookies.Получить(Cookie.Домен) = Неопределено Тогда
ХранилищеCookies[Cookie.Домен] = Новый Соответствие;
КонецЕсли;
Если ХранилищеCookies[Cookie.Домен].Получить(Cookie.Путь) = Неопределено Тогда
ХранилищеCookies[Cookie.Домен][Cookie.Путь] = Новый Соответствие;
КонецЕсли;
Если ХранилищеCookies[Cookie.Домен][Cookie.Путь].Получить(Cookie.Наименование) = Неопределено ИЛИ Замещать Тогда
ХранилищеCookies[Cookie.Домен][Cookie.Путь][Cookie.Наименование] = Cookie;
КонецЕсли;
КонецПроцедуры
Функция ДобавитьЛидирующуюТочку(Знач Домен)
Если Не СтрНачинаетсяС(Домен, ".") Тогда
Домен = "." + Домен;
КонецЕсли;
Возврат Домен;
КонецФункции
Процедура ЗаполнитьСписокОтфильтрованнымиCookies(Cookies, СтруктураURL, Список)
Для Каждого Cookie Из Cookies Цикл
Если Cookie.Значение.ТолькоБезопасноеСоединение = Истина И СтруктураURL.Схема <> "https" Тогда
Продолжить;
КонецЕсли;
// INFO: проверка срока действия игнорируется (Cookie.Значение.СрокДействия)
// INFO: проверка порта игнорируется
Список.Добавить(Cookie.Значение);
КонецЦикла;
КонецПроцедуры
Функция ОтобратьCookiesДляЗапроса(СтруктураURL, Cookies)
СерверВЗапросе = ДобавитьЛидирующуюТочку(СтруктураURL.Сервер);
Результат = Новый Массив;
Для Каждого Домен Из Cookies Цикл
ДоменВCookie = ДобавитьЛидирующуюТочку(Домен.Ключ);
Если Не СтрЗаканчиваетсяНа(СерверВЗапросе, Домен.Ключ) Тогда
Продолжить;
КонецЕсли;
Для Каждого Путь Из Домен.Значение Цикл
Если Не СтрНачинаетсяС(СтруктураURL.Путь, Путь.Ключ) Тогда
Продолжить;
КонецЕсли;
ЗаполнитьСписокОтфильтрованнымиCookies(Путь.Значение, СтруктураURL, Результат);
КонецЦикла;
КонецЦикла;
Возврат Результат;
КонецФункции
Функция ПодготовитьЗаголовокCookie(ПодготовленныйЗапрос)
СтруктураURL = РазобратьURL(ПодготовленныйЗапрос.URL);