Page tree

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
languagephp
titlerest-example.php
linenumberstrue
collapsetrue
<?php
$hoper_url = 'https://hydra.hoper.url/rest/v2/';
$hoper_login = '########';
$hoper_password = '********';
$http_timeout = 60;

$search_string = 'latera';
$search_subtype = 2001;

$http_headers = [
    'Content-Type: application/json',
    'Accept: application/json',
];

$curl_auth = curl_init();
curl_setopt($curl_auth, CURLOPT_POST, true);
curl_setopt($curl_auth, CURLOPT_URL, $hoper_url . "login");
curl_setopt($curl_auth, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_auth, CURLOPT_HTTPHEADER, $http_headers);
curl_setopt($curl_auth, CURLOPT_TIMEOUT, $http_timeout);
curl_setopt($curl_auth, CURLOPT_POSTFIELDS, json_encode(
    ["session" => ["login" => $hoper_login, "password" => $hoper_password]]
));

$auth_response = curl_exec($curl_auth);
$auth_status = curl_getinfo($curl_auth, CURLINFO_HTTP_CODE);
curl_close($curl_auth);

if ($auth_status != 201) {
    echo "Auth error (" . $auth_status . "): " . $auth_response . "\n";
    exit(1);
}

$auth_token = json_decode($auth_response, true)['session']['token'];
$http_headers[] = 'Authorization: Token token=' . $auth_token;

$curl_search = curl_init();
curl_setopt($curl_search, CURLOPT_URL,
    $hoper_url . "search?result_subtype_id=" . $search_subtype . "&query=" . $search_string
);
curl_setopt($curl_search, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_search, CURLOPT_HTTPHEADER, $http_headers);
curl_setopt($curl_search, CURLOPT_TIMEOUT, $http_timeout);

$search_response = curl_exec($curl_search);
$search_status = curl_getinfo($curl_search, CURLINFO_HTTP_CODE);

if ($search_status == 200) {
    $search_result = json_decode($search_response, true);
    foreach ($search_result['search_results'] as $entity) {
        echo "Customer: " . $entity['n_entity_id'] . ": " . $entity['vc_result_name'] . "\n";
    }
} else {
    echo "Invalid response (" . $search_status . "): " . $search_response . "\n";
}


Java

Пример с использованием Apache HttpComponents (org.apache.httpcomponents) и json-java (org.json)

Импортируем необходимые библиотеки

Code Block
languagejava
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;

Создаём стартовый класс и метод

Code Block
languagejava
public class RestAPI {

  public static void main(String[] args) {

Задаём параметры подключения к офису оператора связи:

Code Block
languagejava
String hoperUrl = "https://hydra.hoper.url/rest/v2/";
String hoperLogin = "########";
String hoperPassword = "********";
int httpTimeout = 60;

Задаём параметры поиска. Строка поиска - latera, тип 2001 - поиск по абонентам

Code Block
languagejava
String searchString = "latera";
int searchSubtype = 2001;

Для работы с REST необходимо авторизоваться и получить токен для дальнейшего выполнения запросов.

Чтобы получить токен, подготавливаем JSON для запроса {"session": {"login": "########", "password": "********"}}

Code Block
languagejava
JSONObject authParamsCredentials = new JSONObject();
authParamsCredentials.put("login", hoperLogin);
authParamsCredentials.put("password", hoperPassword);
JSONObject authParams = new JSONObject();
authParams.put("session", authParamsCredentials);

Подготавливаем конфигурацию http-клиента, указываем в ней использование таймаута выполнения запроса и создаём http-клиент

Code Block
languagejava
RequestConfig config = RequestConfig.custom()
    .setSocketTimeout(httpTimeout * 1000).build();
try (CloseableHttpClient httpclient = HttpClientBuilder.create().setDefaultRequestConfig(config)
    .build()) {

Отправляем POST запрос /rest/v2/login с подготовленными параметрами

Code Block
languagejava
HttpPost authRequest = new HttpPost(hoperUrl + "login");
HttpEntity stringEntity = new StringEntity(authParams.toString(),
    ContentType.APPLICATION_JSON);
authRequest.setEntity(stringEntity);
CloseableHttpResponse authResponse = httpclient.execute(authRequest);

Если запрос выполнен успешно, получаем токен из ответа сервера. Если авторизация не выполнилась успешно, завершаем работу скриптау

Code Block
languagejava
String authToken = "";
if (authResponse.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
  JSONObject authResponseData = new JSONObject(
      EntityUtils.toString(authResponse.getEntity()));
  authToken = authResponseData.getJSONObject("session").getString("token");
} else {
  System.err.println("Auth error (" + authResponse.getStatusLine().getStatusCode() + "): "
      + EntityUtils.toString(authResponse.getEntity()));
  System.exit(1);
}

Отправляем GET-запрос на поиск, добавляя в него заголовок Authorization со значением Token token=RECEIVED_TOKEN

Code Block
languagejava
String getUrl = hoperUrl + "search?result_subtype_id=" +
    searchSubtype +
    "&query=" +
    searchString;
HttpGet searchRequest = new HttpGet(getUrl);
searchRequest.addHeader("Authorization", "Token token=" + authToken);
CloseableHttpResponse searchResponse = httpclient.execute(searchRequest);

Если запрос выполнен успешно, по каждой найденной сущности выведем её идентификатор и наименование из результата поиска. Если запрос выполнился с ошибкой, выведем предупреждение с полученным от сервера ответом.

Code Block
languagejava
if (searchResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
  JSONObject searchResponseData = new JSONObject(
      EntityUtils.toString(searchResponse.getEntity()));
  JSONArray searchResults = searchResponseData.getJSONArray("search_results");

  for (int i = 0; i < searchResults.length(); i++) {
    JSONObject row = (JSONObject) searchResults.get(i);
    System.out.println(
        "Customer " + row.getInt("n_entity_id") + ": " + row.getString("vc_result_name"));
  }
} else {
  System.err.println(
      "Invalid response (" + searchResponse.getStatusLine().getStatusCode() + "): "
          + EntityUtils.toString(searchResponse.getEntity()));
}

Завершаем блок try, метод main и класс

Code Block
languagejava
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
}


Полная версия

Code Block
titlebuild.gradle
collapsetrue
plugins {
    id 'java'
    id 'application'
}

group 'org.example'
version '1.0-SNAPSHOT'

mainClassName='RestAPI'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.json:json:20220320'
    implementation 'org.apache.httpcomponents:httpclient:4.5.13'
}


Code Block
titlesettings.gradle
collapsetrue
rootProject.name = 'java-rest-example'


Code Block
languagejava
titlesrc/main/java/RestAPI.java
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;

public class RestAPI {

  public static void main(String[] args) {
    String hoperUrl = "https://hydra.hoper.url/rest/v2/";
    String hoperLogin = "########";
    String hoperPassword = "********";
    int httpTimeout = 60;

    String searchString = "latera";
    int searchSubtype = 2001;

    JSONObject authParamsCredentials = new JSONObject();
    authParamsCredentials.put("login", hoperLogin);
    authParamsCredentials.put("password", hoperPassword);
    JSONObject authParams = new JSONObject();
    authParams.put("session", authParamsCredentials);

    RequestConfig config = RequestConfig.custom()
        .setSocketTimeout(httpTimeout * 1000).build();

    try (CloseableHttpClient httpclient = HttpClientBuilder.create().setDefaultRequestConfig(config)
        .build()) {
      HttpPost authRequest = new HttpPost(hoperUrl + "login");
      HttpEntity stringEntity = new StringEntity(authParams.toString(),
          ContentType.APPLICATION_JSON);
      authRequest.setEntity(stringEntity);
      CloseableHttpResponse authResponse = httpclient.execute(authRequest);

      String authToken = "";
      if (authResponse.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
        JSONObject authResponseData = new JSONObject(
            EntityUtils.toString(authResponse.getEntity()));
        authToken = authResponseData.getJSONObject("session").getString("token");
      } else {
        System.err.println("Auth error (" + authResponse.getStatusLine().getStatusCode() + "): "
            + EntityUtils.toString(authResponse.getEntity()));
        System.exit(1);
      }

      String getUrl = hoperUrl + "search?result_subtype_id=" +
          searchSubtype +
          "&query=" +
          searchString;
      HttpGet searchRequest = new HttpGet(getUrl);
      searchRequest.addHeader("Authorization", "Token token=" + authToken);
      CloseableHttpResponse searchResponse = httpclient.execute(searchRequest);

      if (searchResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        JSONObject searchResponseData = new JSONObject(
            EntityUtils.toString(searchResponse.getEntity()));
        JSONArray searchResults = searchResponseData.getJSONArray("search_results");

        for (int i = 0; i < searchResults.length(); i++) {
          JSONObject row = (JSONObject) searchResults.get(i);
          System.out.println(
              "Customer " + row.getInt("n_entity_id") + ": " + row.getString("vc_result_name"));
        }
      } else {
        System.err.println(
            "Invalid response (" + searchResponse.getStatusLine().getStatusCode() + "): "
                + EntityUtils.toString(searchResponse.getEntity()));
      }

    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
}