|
Как написать такой post запрос в 1С? | ☑ | ||
---|---|---|---|---|
0
Глист
14.11.14
✎
14:26
|
Собственно текст запроса
POST https://api.mailersoft.com/api/v1/subscribers/{list_id}/import в php выглядит так: $ML_Subscribers = new ML_Subscribers( API_KEY ); $subscribers = array( array( 'email' => '[email protected]', 'name' => 'First name', 'fields' => array( array( 'name' => 'gender', 'value' => "female" ), array( 'name' => 'city', 'value' => "Vilnius" ) ) ), array( 'email' => '[email protected]', 'name' => 'First name', 'fields' => array( array( 'name' => 'gender', 'value' => "male" ), array( 'name' => 'city', 'value' => "Paris" ) ) ) ); $subscribers = $ML_Subscribers->setId( LIST_ID )->addAll( $subscribers, 1 /* set resubscribe to true*/ ); Я делаю следующим образом Попытка WinHttp = Новый COMОбъект("WinHttp.WinHttpRequest.5.1"); WinHttp.Option(2,"utf-8"); WinHttp.Open("POST","https://api.mailersoft.com/api/v1/subscribers/import/",0); WinHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); ПараметрыПОСТ = "id=3005651&[email protected]&id=3005651&[email protected]"; WinHttp.Send(ПараметрыПОСТ); ТекстОтвета = WinHttp.ResponseText(); Исключение Сообщить(ОписаниеОшибки()); КонецПопытки; В результате добавляется только последний имейл, хотя в описании application/x-www-form-urlencoded сказано, что "Это формат для кодирования пар ключ-значение с возможностью ДУБЛИРОВАНИЯ ключей" Интересует как массив массивов переделать в строку чтобы сервис это распознал. Или как передать структуру или что-топодобное с ключом и значением в пост запрос. |
|||
1
Глист
14.11.14
✎
14:45
|
up
|
|||
2
klis
14.11.14
✎
14:48
|
id[0]=3005651&email[0][email protected]&id[1]=3005651&email[1][email protected] не канает?
|
|||
3
Asmody
14.11.14
✎
14:49
|
так и спросил бы у сервиса, 1С тут при чём?
так, как ты передаешь параметры, на той стороне не должно распознаваться в принципе. ну и кроме того, зачем использовать WinHttpRequest, когда достаточно нативного HTTPСоединение? |
|||
4
Глист
14.11.14
✎
14:55
|
(3) На сервисе одни козлы, говорят пробуйте на php и смотрите какая строка получится. Ая в пхп не шарю,
Не использую HTTPСоединение потому что я не знаю что передавать в первый параметр метода ОТправитьДляОбработки |
|||
5
Глист
14.11.14
✎
14:56
|
(2) не канает
|
|||
6
klis
14.11.14
✎
15:47
|
(5) А исходник объекта ML_Subscribers есть? Что за id у тебя? Почему он два раза один и тот же?
Попробуй такую строку передать: [{"email": "[email protected]"},{"email": "[email protected]"}] |
|||
7
Поpyчик-4
14.11.14
✎
15:53
|
||||
8
Глист
14.11.14
✎
16:10
|
(6) исходник есть
<?php require_once dirname(__FILE__).'/base/ML_Rest.php'; class ML_Subscribers extends ML_Rest { function ML_Subscribers( $api_key ) { $this->name = 'subscribers'; parent::__construct($api_key); } function add( $data = null, $resubscribe = 0 ) { $data['resubscribe'] = $resubscribe; return $this->execute( 'POST', $data ); } function addAll( $subscribers, $resubscribe = 0 ) { $data['resubscribe'] = $resubscribe; $data['subscribers'] = $subscribers; return $this->execute( 'POST', $data, 'import' ); } function get( $email = null, $history = 0 ) { $this->setId( null ); $data['email'] = $email; $data['history'] = $history; return $this->execute( 'GET', $data ); } function remove( $email = null ) { $data['email'] = $email; return $this->execute( 'DELETE', $data ); } function unsubscribe( $email ) { $data['email'] = $email; return $this->execute( 'POST', $data, 'unsubscribe' ); } } ?> id - это номер группы рассылки в которую будет помещен данный имейл. Со строкой не вышло |
|||
9
Глист
14.11.14
✎
16:14
|
(7) Так а что мне поместить в тело запроса? Какой файл? с каким содержимым?
|
|||
10
klis
14.11.14
✎
16:15
|
(8) Ок, а исходник ML_Rest?)
|
|||
11
Глист
14.11.14
✎
16:21
|
(10) <?php
require_once dirname(__FILE__).'/ML_Rest_Base.php'; class ML_Rest extends ML_Rest_Base { var $name = ''; var $id = null; function __construct( $api_key ) { parent::__construct(); $this->apiKey = $api_key; $this->path = $this->url . $this->name . '/'; } public function setId( $id ) { $this->id = $id; if ( $this->id ) $this->path = $this->url . $this->name . '/' . $id . '/'; else $this->path = $this->url . $this->name . '/'; return $this; } public function getAll( $data = null ) { return $this->execute( 'GET', $data ); } public function get( $data = null ) { if (!$this->id) throw new InvalidArgumentException('ID is not set.'); return $this->execute( 'GET', $data ); } public function add( $data = null ) { return $this->execute( 'POST', $data ); } public function put( $data = null) { return $this->execute( 'PUT', $data ); } public function remove( $data = null ) { return $this->execute( 'DELETE', $data ); } } ?> |
|||
12
Глист
14.11.14
✎
16:22
|
а вот ML_Rest_Base
<?php class ML_Rest_Base { protected $url; protected $verb; protected $requestBody; protected $requestLength; protected $username; protected $password; protected $acceptType; protected $responseBody; protected $responseInfo; protected $apiKey = ''; protected $path = ''; private $request_url; public function __construct ($url = 'https://api.mailersoft.com/api/v1/', $verb = 'GET') { $this->url = $url; $this->verb = $verb; $this->requestLength = 0; $this->username = null; $this->password = null; $this->acceptType = 'application/json'; $this->responseBody = null; $this->responseInfo = null; } public function flush () { $this->requestBody = null; $this->requestLength = 0; $this->verb = 'GET'; $this->responseBody = null; $this->responseInfo = null; } public function execute ( $method = null, $data = null, $action = null ) { $ch = curl_init(); $this->setAuth($ch); if ( $method ) $this->verb = $method; $this->requestBody = $data; $this->buildPostBody(); if ( $action ) $action .= '/'; try { switch (strtoupper($this->verb)) { case 'GET': $this->executeGet( $ch, $action ); break; case 'POST': $this->executePost( $ch, $action ); break; case 'PUT': $this->executePut( $ch, $action ); break; case 'DELETE': $this->executeDelete( $ch, $action ); break; default: throw new InvalidArgumentException('Current verb (' . $this->verb . ') is an invalid REST verb.'); } } catch (InvalidArgumentException $e) { curl_close($ch); throw $e; } catch (Exception $e) { curl_close($ch); throw $e; } return json_decode( $this->responseBody, true ); } public function buildPostBody () { $data = $this->requestBody; $data['apiKey'] = $this->apiKey; if (!is_array($data)) { throw new InvalidArgumentException('Invalid data input for postBody. Array expected'); } $data = http_build_query($data, '', '&'); $this->requestBody = $data; } protected function executeGet ( $ch, $action ) { $this->request_url = $this->path . $action . ( strpos( $this->path, '?' ) === false ? '?' : '&' ) . $this->requestBody; $this->doExecute($ch); } protected function executePost ( $ch, $action ) { $this->request_url = $this->path . $action; curl_setopt($ch, CURLOPT_POSTFIELDS, $this->requestBody); curl_setopt($ch, CURLOPT_POST, 1); $this->doExecute($ch); } protected function executePut ( $ch, $action ) { $this->request_url = $this->path . $action; $this->requestLength = strlen($this->requestBody); $fh = fopen('php://memory', 'rw'); fwrite($fh, $this->requestBody); rewind($fh); curl_setopt($ch, CURLOPT_INFILE, $fh); curl_setopt($ch, CURLOPT_INFILESIZE, $this->requestLength); curl_setopt($ch, CURLOPT_PUT, true); $this->doExecute($ch); fclose($fh); } protected function executeDelete ( $ch, $action ) { $this->request_url = $this->path . $action . ( strpos( $this->path, '?' ) === false ? '?' : '&' ) . $this->requestBody; curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE'); $this->doExecute($ch); } protected function doExecute (&$curlHandle) { $this->setCurlOpts($curlHandle); $this->responseBody = curl_exec($curlHandle); $this->responseInfo = curl_getinfo($curlHandle); curl_close($curlHandle); } protected function setCurlOpts (&$curlHandle) { //curl_setopt($curlHandle, CURLOPT_TIMEOUT, 10); curl_setopt($curlHandle, CURLOPT_URL, $this->request_url); curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true); curl_setopt($curlHandle, CURLOPT_HTTPHEADER, array ('Accept: ' . $this->acceptType)); curl_setopt($curlHandle, CURLOPT_SSL_VERIFYHOST, false ); curl_setopt($curlHandle, CURLOPT_SSL_VERIFYPEER, false ); curl_setopt($curlHandle, CURLOPT_FOLLOWLOCATION, true ); } protected function setAuth (&$curlHandle) { if ($this->username !== null && $this->password !== null) { curl_setopt($curlHandle, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST); curl_setopt($curlHandle, CURLOPT_USERPWD, $this->username . ':' . $this->password); } } public function getAcceptType () { return $this->acceptType; } public function setAcceptType ($acceptType) { $this->acceptType = $acceptType; } public function getPassword () { return $this->password; } public function setPassword ($password) { $this->password = $password; } public function getResponseBody () { return $this->responseBody; } public function getResponseInfo () { return $this->responseInfo; } public function getUrl () { return $this->url; } public function setUrl ($url) { $this->url = $url; } public function getUsername () { return $this->username; } public function setUsername ($username) { $this->username = $username; } public function getVerb () { return $this->verb; } public function setVerb ($verb) { $this->verb = $verb; } } |
|||
13
Глист
14.11.14
✎
16:27
|
кажется понял, нужно расписать данные массива так как делает функция пхп http_build_query()
|
|||
14
klis
14.11.14
✎
16:30
|
(13) Ну да, обогнал)
Строка из твоего примера будет выглядеть так: [code]apiKey=0123456789&subscribers%5B0%5D%5Bemail%5D=wow203%40gmail.com&subscribers%5B1%5D%5Bemail%5D=wow201%40gmail.com[/code] где apiKey - твой секретный ключ api. А id передается не в запросе, а в url'е вместо {list_id} |
|||
15
klis
14.11.14
✎
16:33
|
(14)+ в читабельном виде это выглядит так:
apiKey=0123456789&subscribers[0][email][email protected]&subscribers[1][email][email protected] просто скобки, собаки и другие extended ascii кодируются шестнадцатиричными кодами |
|||
16
Глист
14.11.14
✎
16:35
|
(14) (15) Спасибо огромное за помощь! А в 1с случайно такой функции нет?
А на счет того что id передается не в запросе, а в url'е вместо {list_id}. это да, но если написать вот так api.mailersoft.com/api/v1/subscribers//import то можно и в запросе |
Форум | Правила | Описание | Объявления | Секции | Поиск | Книга знаний | Вики-миста |