Page tree

Versions Compared

Key

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

...

Пример поиска абонентов по коду.

Eсли Если планируется значительное количество запросов, следует установить отдельную копию приложения hoper, чтобы работа с REST API не вызывала задержек в работе операторов через веб-интерфейс.

Основной язык программирования, используемый для разработки интеграций, требующих взаимодействия с API - Python.

Python

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

...

Code Block
languagejava
titlesrc/main/java/RestAPI.java
linenumberstrue
collapsetrue
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);
    }
  }
}