public JSONObject textToSpeech(Object input) {
    JSONObject args = (JSONObject) JSObjectConverter.scriptableToJSON((Scriptable) input);
    JSONObject theReturn = null;
    URL url = null;
    try {
      theReturn = new JSONObject();
      String host = (String) args.get(ATTConstant.ARG_URL);
      url = new URL(host);

      HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

      conn.setDoOutput(true);
      conn.setDoInput(true);

      conn.setRequestMethod("POST");
      conn.setRequestProperty("Authorization", (String) args.get(ATTConstant.ARG_TOKEN));

      if (args.containsKey(ATTConstant.ARG_HEADER_CONTENT_TYPE)) {
        conn.setRequestProperty(
            "Content-Type", (String) args.get(ATTConstant.ARG_HEADER_CONTENT_TYPE));
      } else {
        conn.setRequestProperty("Content-Type", "text/plain");
      }

      if (args.containsKey(ATTConstant.ARG_HEADER_ACCEPT)) {
        conn.setRequestProperty(
            ATTConstant.ARG_HEADER_ACCEPT, (String) args.get(ATTConstant.ARG_HEADER_ACCEPT));
      } else {
        conn.setRequestProperty(ATTConstant.ARG_HEADER_ACCEPT, ATTConstant.VAL_CONTENT_TYPE_AMRWB);
      }

      if (args.containsKey(ATTConstant.ARG_HEADER_CONTENT_LANGUAGE)) {
        conn.setRequestProperty(
            "Content-Language", (String) args.get(ATTConstant.ARG_HEADER_CONTENT_LANGUAGE));
      } else {
        conn.setRequestProperty("Content-Language", ATTConstant.VAL_EN_US);
      }

      String body = (String) args.get(ATTConstant.ARG_BODY);
      conn.setRequestProperty("Content-Length", Integer.toString(body.length()));

      if (args.containsKey(ATTConstant.ARG_HEADER_XARG)) {
        conn.setRequestProperty("X-Arg", (String) args.get(ATTConstant.ARG_HEADER_XARG));
      }

      String clientSdk = "ClientSdk=att.worklight." + ATTConstant.ARG_HEADER_XARG_VERSION;
      if (args.containsKey(ATTConstant.ARG_HEADER_XARG)) {
        conn.setRequestProperty(
            "X-Arg", (String) args.get(ATTConstant.ARG_HEADER_XARG) + "," + clientSdk);
      } else {
        conn.setRequestProperty("X-Arg", clientSdk);
      }

      System.out.println("********* TextToSpeech JAVA ADAPTER LOGS ***********");

      OutputStreamWriter outStream = new OutputStreamWriter(conn.getOutputStream());
      outStream.write(body);
      outStream.flush();
      outStream.close();

      /*@SuppressWarnings("unchecked")
      Map<String,List<String>> header = conn.getHeaderFields();
      for (String key: header.keySet ())
         System.out.println (key+": "+conn.getHeaderField (key));
         */

      int responseCode = conn.getResponseCode();
      String responseCodeString = Integer.toString(responseCode);
      JSONObject response = new JSONObject();
      response.put("code", responseCodeString);

      if (responseCode < 400) { // Handle binary response
        // Get all the headers to pass through
        // Read the response and convert to base64
        BufferedInputStream inputStream = new BufferedInputStream(conn.getInputStream());

        int iContentLength = conn.getHeaderFieldInt("Content-Length", 0);
        int totalRead = 0;
        int currentRead = 0;
        byte[] binaryBody = new byte[iContentLength];
        do {
          currentRead = inputStream.read(binaryBody, totalRead, iContentLength - totalRead);
          totalRead += currentRead;
        } while (totalRead < iContentLength);

        String encodedBody = Base64.encode(binaryBody);
        Base64.encode(binaryBody, iContentLength);
        response.put("content", encodedBody.toString());
        response.put("contentType", conn.getHeaderField("Content-Type") + ";base64");
        response.put("contentLength", conn.getHeaderField("Content-Length"));
      } else { // handle html response
        StringBuffer errorString = new StringBuffer();
        BufferedReader is = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
        String str;
        while (null != ((str = is.readLine()))) {
          errorString.append(str);
        }
        is.close();
        response.put("error", errorString.toString());
      }
      theReturn.put("message", response);
    } catch (Exception e) {
      e.printStackTrace();
      String message = null;
      String code = null;
      if (e.equals(ATTConstant.ERR_INV_STATUS_MSG)) {
        code = ATTConstant.ERR_INV_STATUS_CODE;
        message = ATTConstant.ERR_INV_STATUS_MSG;
      } else {
        code = ATTConstant.ERR_PROCESS_REQ_CODE;
        message = e.getLocalizedMessage(); // ATTConstant.ERR_PROCESS_REQ_MSG;
      }
      theReturn.put(code, message);
      return theReturn;
    } finally {
      args.clear();
      args = null;
    }
    return theReturn;
  }
  public JSONObject speechToText(Object input) {
    JSONObject args = (JSONObject) JSObjectConverter.scriptableToJSON((Scriptable) input);
    JSONObject theReturn = null;
    URL url = null;

    try {
      System.out.println("********* Speech JAVA ADAPTER LOGS ***********");
      theReturn = new JSONObject();
      String host = (String) args.get(ATTConstant.ARG_URL);
      url = new URL(host);
      HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
      // HttpURLConnection conn = (HttpURLConnection) url.openConnection();

      conn.setDoOutput(true);
      conn.setDoInput(true);
      conn.setRequestMethod("POST");
      // conn.setRequestMethod("GET");
      conn.setRequestProperty("Authorization", (String) args.get(ATTConstant.ARG_TOKEN));
      if (args.containsKey(ATTConstant.ARG_HEADER_CONTENT_TYPE)) {
        conn.setRequestProperty(
            "Content-Type", (String) args.get(ATTConstant.ARG_HEADER_CONTENT_TYPE));
      }

      if (args.containsKey(ATTConstant.ARG_HEADER_CONTENT_LANGUAGE)) {
        conn.setRequestProperty(
            "Content-Language", (String) args.get(ATTConstant.ARG_HEADER_CONTENT_LANGUAGE));
      } else {
        conn.setRequestProperty("Content-Language", ATTConstant.VAL_EN_US);
      }

      if (args.containsKey(ATTConstant.ARG_HEADER_XSPEECH_CONTEXT)) {
        conn.setRequestProperty(
            "X-SpeechContext", (String) args.get(ATTConstant.ARG_HEADER_XSPEECH_CONTEXT));
      }

      if (args.containsKey(ATTConstant.ARG_HEADER_XSPEECH_SUBCONTEXT)) {
        conn.setRequestProperty(
            "X-SpeechSubContext", (String) args.get(ATTConstant.ARG_HEADER_XSPEECH_SUBCONTEXT));
      }

      if (args.containsKey(ATTConstant.ARG_HEADER_ACCEPT)) {
        conn.setRequestProperty("Accept", (String) args.get(ATTConstant.ARG_HEADER_ACCEPT));
      }

      String clientSdk =
          "ClientSdk=att_worklight-"
              + (String) args.get("platform")
              + "-"
              + ATTConstant.ARG_HEADER_XARG_VERSION;
      if (args.containsKey(ATTConstant.ARG_HEADER_XARG)) {
        conn.setRequestProperty(
            "X-Arg", (String) args.get(ATTConstant.ARG_HEADER_XARG) + "," + clientSdk);
      } else {
        conn.setRequestProperty("X-Arg", clientSdk);
      }

      String base64AudioString = (String) args.get(ATTConstant.ARG_FILEOBJECT);
      Logger logger = Logger.getLogger("Speech Adapter");
      logger.info("The received string is: " + base64AudioString);

      byte[] decoded = Base64.decode(base64AudioString);

      OutputStream wr = conn.getOutputStream();

      wr.write(decoded);
      wr.flush();
      wr.close();
      // System.out.println("********* Speech JAVA ADAPTER LOGS ***********");
      // System.out.println("Headers***********");
      // @SuppressWarnings("unchecked")
      // Map<String,List<String>> header = conn.getHeaderFields();
      // for (String key: header.keySet ())
      //   System.out.println (key+": "+conn.getHeaderField (key));

      JSONObject response = new JSONObject();
      if (conn.getResponseCode() < 400) {
        response = JSONObject.parse(conn.getInputStream());
      } else {
        StringBuffer errorString = new StringBuffer();
        BufferedReader is = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
        String str;
        while (null != ((str = is.readLine()))) {
          errorString.append(str);
        }
        is.close();
        response.put("error", errorString.toString());
      }

      theReturn.put("message", response);
    } catch (Exception e) {
      e.printStackTrace();
      String message = null;
      String code = null;
      if (e.equals(ATTConstant.ERR_INV_STATUS_MSG)) {
        code = ATTConstant.ERR_INV_STATUS_CODE;
        message = ATTConstant.ERR_INV_STATUS_MSG;
      } else {
        code = ATTConstant.ERR_PROCESS_REQ_CODE;
        message =
            url.toString() + " " + e.getLocalizedMessage(); // ATTConstant.ERR_PROCESS_REQ_MSG;
      }

      theReturn.put(code, message);
      return theReturn;
    } finally {
      args.clear();
      args = null;
    }
    return theReturn;
  }
  /**
   * The main RESTful GET method; the other one ({@link #make_restful_get(String, String, int)})
   * calls this one with a pre-populated logging parameter.
   *
   * @param baseUrl A {@link String} URL to request from.
   * @param tag A {@link String} tag for logging/analytics purposes.
   * @param timeout An {@link Integer} value containing the number of milliseconds to wait before
   *     considering a server request to have timed out.
   * @param log A {@link Boolean} value that specifies whether debug logging should be enabled for
   *     this request or not.
   * @return A {@link ServerResponse} object containing the result of the RESTful request.
   */
  private ServerResponse make_restful_get(
      String baseUrl, String tag, int timeout, int retryNumber, boolean log) {
    String modifiedUrl = baseUrl;
    JSONObject getParameters = new JSONObject();
    HttpsURLConnection connection = null;
    if (timeout <= 0) {
      timeout = DEFAULT_TIMEOUT;
    }
    if (addCommonParams(getParameters, retryNumber)) {
      modifiedUrl += this.convertJSONtoString(getParameters);
    } else {
      return new ServerResponse(tag, NO_BRANCH_KEY_STATUS);
    }

    try {
      if (log) PrefHelper.Debug("BranchSDK", "getting " + modifiedUrl);
      URL urlObject = new URL(modifiedUrl);
      connection = (HttpsURLConnection) urlObject.openConnection();
      connection.setConnectTimeout(timeout);
      connection.setReadTimeout(timeout);

      if (connection.getResponseCode() >= 500 && retryNumber < prefHelper_.getRetryCount()) {
        try {
          Thread.sleep(prefHelper_.getRetryInterval());
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        retryNumber++;
        return make_restful_get(baseUrl, tag, timeout, retryNumber, log);
      } else {
        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK
            && connection.getErrorStream() != null) {
          return processEntityForJSON(
              connection.getErrorStream(), connection.getResponseCode(), tag, log, null);
        } else {
          return processEntityForJSON(
              connection.getInputStream(), connection.getResponseCode(), tag, log, null);
        }
      }
    } catch (SocketException ex) {
      if (log)
        PrefHelper.Debug(getClass().getSimpleName(), "Http connect exception: " + ex.getMessage());
      return new ServerResponse(tag, NO_CONNECTIVITY_STATUS);
    } catch (UnknownHostException ex) {
      if (log)
        PrefHelper.Debug(getClass().getSimpleName(), "Http connect exception: " + ex.getMessage());
      return new ServerResponse(tag, NO_CONNECTIVITY_STATUS);
    } catch (IOException ex) {
      if (log) PrefHelper.Debug(getClass().getSimpleName(), "IO exception: " + ex.getMessage());
      return new ServerResponse(tag, 500);
    } finally {
      if (connection != null) {
        connection.disconnect();
      }
    }
  }
  /**
   * Synchronous call for logging in
   *
   * @param httpBody
   * @return The data from the server as a string, in almost all cases JSON
   * @throws MalformedURLException
   * @throws IOException
   * @throws JSONException
   */
  public static String getLoginResponse(Bundle httpBody) throws MalformedURLException, IOException {
    String response = "";
    URL url = new URL(WebServiceAuthProvider.tokenURL());
    HttpsURLConnection connection = createSecureConnection(url);
    String authString = "mobile_android:secret";
    String authValue = "Basic " + Base64.encodeToString(authString.getBytes(), Base64.NO_WRAP);

    connection.setRequestMethod("POST");
    connection.setRequestProperty("Authorization", authValue);
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.connect();

    OutputStream os = new BufferedOutputStream(connection.getOutputStream());
    os.write(encodePostBody(httpBody).getBytes());
    os.flush();
    try {
      LoggingUtils.d(LOG_TAG, connection.toString());
      response = readFromStream(connection.getInputStream());
    } catch (MalformedURLException e) {
      LoggingUtils.e(
          LOG_TAG,
          "Error reading stream \""
              + connection.getInputStream()
              + "\". "
              + e.getLocalizedMessage(),
          null);
    } catch (IOException e) {
      response = readFromStream(connection.getErrorStream());
    } finally {
      connection.disconnect();
    }

    return response;
  }
  /**
   * Executa a operação da API informando um Builder para a requisição e resposta.
   *
   * @param requestBuilder é uma instância de {@link AkatusRequestBuilder} responsável pela criação
   *     do corpo da requisição.
   * @param responseBuilder é uma instância de {@link AkatusResponseBuilder} responsável pela
   *     criação do objeto que representa a resposta.
   * @return Uma instância de {@link AkatusResponse} com a resposta da operação.
   */
  public AkatusResponse execute(
      AkatusRequestBuilder requestBuilder, AkatusResponseBuilder responseBuilder) {

    AkatusResponse response = new AkatusResponse();

    try {
      final URL url = new URL(akatus.getHost() + getPath());
      final HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

      connection.setDoInput(true);
      connection.setDoOutput(true);
      connection.setRequestMethod("POST");
      connection.setRequestProperty("Content-Type", requestBuilder.getContentType());

      final OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());

      writer.write(requestBuilder.build(this));
      writer.flush();

      try {
        response = responseBuilder.build(readResponse(connection.getInputStream()));
      } catch (final IOException e) {
        response = responseBuilder.build(readResponse(connection.getErrorStream()));
      }
    } catch (final Exception e) {
      Logger.getLogger(AkatusOperation.class.getName())
          .throwing(this.getClass().getName(), "execute", e);
    }

    return response;
  }
예제 #6
0
  protected static String getResponseForXPayToken(
      String endpoint, String xpaytoken, String payload, String method, String crId)
      throws IOException {

    logRequestBody(payload, endpoint, xpaytoken, crId);
    HttpsURLConnection conn = null;
    OutputStream os;
    BufferedReader br = null;
    InputStream is;
    String output;
    String op = "";

    URL url1 = new URL(endpoint);
    //	getCertificate();

    conn = (HttpsURLConnection) url1.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod(method);
    conn.setRequestProperty("Content-Type", "application/json");
    conn.setRequestProperty("x-request-id", "1234");
    conn.setRequestProperty("x-pay-token", xpaytoken);
    conn.setRequestProperty("X-CORRELATION-ID", crId);

    if (!StringUtils.isEmpty(payload)) {
      os = conn.getOutputStream();
      os.write(payload.getBytes());
      os.flush();
    }
    if (conn.getResponseCode() >= 400) {
      is = conn.getErrorStream();
    } else {
      is = conn.getInputStream();
    }
    if (is != null) {
      br = new BufferedReader(new InputStreamReader(is));
      while ((output = br.readLine()) != null) {
        op += output;
      }
    }

    // Log the response Headers
    Map<String, List<String>> map = conn.getHeaderFields();
    // for (Map.Entry<String, List<String>> entry : map.entrySet()) {
    logger.info("Response Headers: " + map.toString());
    // }

    conn.disconnect();
    logResponseBody(op);

    return op;
  }
  // return null means successfully write to server
  static Response writeStream(HttpsURLConnection connection, String content) {
    BufferedOutputStream out = null;
    Response response = null;
    try {
      out = new BufferedOutputStream(connection.getOutputStream());
      out.write(content.getBytes("UTF-8"));
      out.flush();
    } catch (IOException e) {
      e.printStackTrace();

      try {
        // it could be caused by 400 and so on
        response = new Response();

        BufferedReader reader =
            new BufferedReader(new InputStreamReader(connection.getErrorStream(), "UTF-8"));

        StringBuilder stringBuilder = new StringBuilder();

        int tmp;
        while ((tmp = reader.read()) != -1) {
          stringBuilder.append((char) tmp);
        }

        response.code = connection.getResponseCode();
        response.content = stringBuilder.toString();

      } catch (IOException e1) {
        response = new Response();
        response.content = e1.getMessage();
        response.code = -1;
        e1.printStackTrace();
      } catch (Exception ex) {
        // if user directly shutdowns network when trying to write to server
        // there could be NullPointerException or SSLException
        response = new Response();
        response.content = ex.getMessage();
        response.code = -1;
        ex.printStackTrace();
      }
    } finally {
      try {
        if (out != null) out.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    return response;
  }
  /**
   * Synchronous call for logging out
   *
   * @return The data from the server as a string, in almost all cases JSON
   * @throws MalformedURLException
   * @throws IOException
   * @throws JSONException
   */
  public static String getLogoutResponse(Context context)
      throws MalformedURLException, IOException, JSONException {
    // Refresh if necessary
    if (WebServiceAuthProvider.tokenExpiredHint(context)) {
      WebServiceAuthProvider.refreshAccessToken(context);
    }

    boolean refreshLimitReached = false;
    int refreshed = 0;

    String response = "";
    while (!refreshLimitReached) {
      // If we have refreshed max number of times, we will not do so again
      if (refreshed == 1) {
        refreshLimitReached = true;
      }

      URL url = new URL(urlForLogout(context));
      HttpsURLConnection connection = createSecureConnection(url);
      String authValue = "Bearer " + SDKSettings.getSharedPreferenceString(context, "access_token");

      connection.setRequestMethod("POST");
      connection.setRequestProperty("Authorization", authValue);
      connection.setDoOutput(true);
      connection.setDoInput(true);
      connection.connect();

      try {
        LoggingUtils.d(LOG_TAG, "LogoutResponse" + connection.toString());
        response = readFromStream(connection.getInputStream());
      } catch (MalformedURLException e) {
        LoggingUtils.e(
            LOG_TAG,
            "Error reading stream \""
                + connection.getInputStream()
                + "\". "
                + e.getLocalizedMessage(),
            null);
      } catch (IOException e) {
        response = readFromStream(connection.getErrorStream());
      } finally {
        connection.disconnect();
      }

      // Allow for calls to return nothing
      if (response.length() == 0) {
        return "";
      }

      // Check for JSON parsing errors (will throw JSONException is can't be parsed)
      JSONObject object = new JSONObject(response);

      // If no error, return response
      if (!object.has("error")) {
        return response;
      }
      // If there is a refresh token error, refresh the token
      else if (object.getString("error").equals("invalid_token")) {
        if (refreshLimitReached) {
          // Give up
          return response;
        } else {
          // Refresh the token
          WebServiceAuthProvider.refreshAccessToken(context);
          refreshed++;
        }
      }
    } // while(!refreshLimitReached)

    return response;
  }
  /**
   * Synchronous call to get a new client credentials token, required for creating new account
   *
   * @param url
   * @param clientCredentialsToken
   * @param httpMethod
   * @param httpBody
   * @return The data from the server as a string, in almost all cases JSON
   * @throws MalformedURLException
   * @throws IOException
   * @throws ProtocolException
   * @throws JSONException
   */
  public static String getClientCredentialsResponse(
      Context context,
      String url,
      String clientCredentialsToken,
      String httpMethod,
      Bundle httpBody)
      throws MalformedURLException, IOException, ProtocolException, JSONException {
    boolean refreshLimitReached = false;
    int refreshed = 0;

    String response = "";
    while (!refreshLimitReached) {
      // If we have refreshed max number of times, we will not do so again
      if (refreshed == 1) {
        refreshLimitReached = true;
      }

      HttpsURLConnection connection = createSecureConnection(new URL(addParameters(context, url)));
      connection.setRequestMethod(httpMethod);
      connection.setDoOutput(true);
      connection.setDoInput(true);
      String authValue = "Bearer " + clientCredentialsToken;
      connection.setRequestProperty("Authorization", authValue);
      connection.connect();

      if (!httpBody.isEmpty()) {
        OutputStream os = new BufferedOutputStream(connection.getOutputStream());
        os.write(encodePostBody(httpBody).getBytes());
        os.flush();
      }

      try {
        LoggingUtils.d(LOG_TAG, connection.toString());
        response = readFromStream(connection.getInputStream());
      } catch (FileNotFoundException e) {
        response = readFromStream(connection.getErrorStream());
      } finally {
        connection.disconnect();
      }

      // Allow for calls to return nothing
      if (response.length() == 0) {
        return "";
      }

      // Check for JSON parsing errors (will throw JSONException is can't be parsed)
      JSONObject object = new JSONObject(response);

      // If no error, return response
      if (!object.has("error")) {
        return response;
      }
      // If there is a refresh token error, refresh the token
      else if (object.getString("error").equals("invalid_token")) {
        if (refreshLimitReached) {
          // Give up
          return response;
        } else {
          // Refresh the token
          WebServiceAuthProvider.refreshAccessToken(context);
          refreshed++;
        }
      }
    } // while(!refreshLimitReached)

    return response;
  }
예제 #10
0
  @SuppressWarnings("UseSpecificCatch")
  private static JSONObject readJsonFromUrl(String urlAddress) {
    JSONObject jsonResult = new JSONObject("{}");
    InputStream inputStream = null;
    URL urlRaw;
    HttpsURLConnection urlConn;
    String jsonText = "";

    try {
      urlRaw = new URL(urlAddress);
      urlConn = (HttpsURLConnection) urlRaw.openConnection();
      urlConn.setDoInput(true);
      urlConn.setRequestMethod("GET");
      urlConn.addRequestProperty("Content-Type", "application/json");
      urlConn.setRequestProperty(
          "User-Agent",
          "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 "
              + "(KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 PhantomBotJ/2015");
      urlConn.connect();

      if (urlConn.getResponseCode() == 200) {
        inputStream = urlConn.getInputStream();
      } else {
        inputStream = urlConn.getErrorStream();
      }

      BufferedReader rd =
          new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
      jsonText = readAll(rd);
      jsonResult = new JSONObject(jsonText);
      fillJSONObject(
          jsonResult, true, "GET", urlAddress, urlConn.getResponseCode(), "", "", jsonText);
    } catch (JSONException ex) {
      fillJSONObject(
          jsonResult, false, "GET", urlAddress, 0, "JSONException", ex.getMessage(), jsonText);
      com.gmt2001.Console.err.printStackTrace(ex);
    } catch (NullPointerException ex) {
      fillJSONObject(
          jsonResult, false, "GET", urlAddress, 0, "NullPointerException", ex.getMessage(), "");
      com.gmt2001.Console.err.printStackTrace(ex);
    } catch (MalformedURLException ex) {
      fillJSONObject(
          jsonResult, false, "GET", urlAddress, 0, "MalformedURLException", ex.getMessage(), "");
      com.gmt2001.Console.err.printStackTrace(ex);
    } catch (SocketTimeoutException ex) {
      fillJSONObject(
          jsonResult, false, "GET", urlAddress, 0, "SocketTimeoutException", ex.getMessage(), "");
      com.gmt2001.Console.err.printStackTrace(ex);
    } catch (IOException ex) {
      fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), "");
      com.gmt2001.Console.err.printStackTrace(ex);
    } catch (Exception ex) {
      fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "Exception", ex.getMessage(), "");
      com.gmt2001.Console.err.printStackTrace(ex);
    } finally {
      if (inputStream != null)
        try {
          inputStream.close();
        } catch (IOException ex) {
          fillJSONObject(
              jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), "");
          com.gmt2001.Console.err.printStackTrace(ex);
        }
    }

    return (jsonResult);
  }
  static Response readStream(HttpsURLConnection connection) {
    Response response = new Response();

    StringBuilder stringBuilder = new StringBuilder();

    BufferedReader reader = null;
    try {

      reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));

      int tmp;
      while ((tmp = reader.read()) != -1) {
        stringBuilder.append((char) tmp);
      }

      response.code = connection.getResponseCode();
      response.content = stringBuilder.toString();
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
      response.code = -1;
      response.content = e.getMessage();
    } catch (IOException e) {
      e.printStackTrace();

      try {
        // it could be caused by 400 and so on

        reader = new BufferedReader(new InputStreamReader(connection.getErrorStream(), "UTF-8"));

        // clear
        stringBuilder.setLength(0);

        int tmp;
        while ((tmp = reader.read()) != -1) {
          stringBuilder.append((char) tmp);
        }

        response.code = connection.getResponseCode();
        response.content = stringBuilder.toString();

      } catch (IOException e1) {
        response.content = e1.getMessage();
        response.code = -1;
        e1.printStackTrace();
      } catch (Exception ex) {
        // if user directly shuts down network when trying to write to server
        // there could be NullPointerException or SSLException
        response.content = ex.getMessage();
        response.code = -1;
        ex.printStackTrace();
      }
    } finally {
      if (reader != null) {
        try {
          reader.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }

    return response;
  }
  /**
   * This is the main HTTREQUEST method
   *
   * @param apiurl the url of the called api
   * @param header header params
   * @param get get params (NOT USED)
   * @return the json object returned by the api
   */
  public String httpRequest(String apiurl, HeaderParams header, PostParams post, boolean isPost) {

    // DEBUG
    DebugUtility.showLog(apiurl);

    URL url;

    try {
      String postParams = "";

      if (post != null) {
        for (int i = 0; i < post.getKey().size(); i++) {
          if (i == 0)
            postParams =
                postParams
                    + post.getKey().get(i)
                    + "="
                    + URLEncoder.encode(post.getValue().get(i), "UTF-8");
          else
            postParams =
                postParams
                    + "&"
                    + post.getKey().get(i)
                    + "="
                    + URLEncoder.encode(post.getValue().get(i), "UTF-8");
        }
      }
      url = new URL(apiurl);

      System.setProperty("http.keepAlive", "false");

      postUrlConnection = (HttpsURLConnection) url.openConnection();
      postUrlConnection.setUseCaches(false);
      postUrlConnection.setDoInput(true);

      header.getKey().add("X-BEINTOO-SDK-VERSION");
      header.getValue().add(BeintooSdkParams.version);

      if (BeintooSdkParams.useSandbox) {
        header.getKey().add("sandbox");
        header.getValue().add("true");
      }
      for (int i = 0; i < header.getKey().size(); i++) {
        postUrlConnection.setRequestProperty(header.getKey().get(i), header.getValue().get(i));
      }

      if (isPost) {
        postUrlConnection.setDoOutput(true);
        postUrlConnection.setRequestMethod("POST");
        postUrlConnection.setRequestProperty(
            "Content-Length", "" + Integer.toString(postParams.getBytes().length));
        DataOutputStream wr = new DataOutputStream(postUrlConnection.getOutputStream());
        wr.writeBytes(postParams);
        wr.flush();
        wr.close();
      } else {
        postUrlConnection.setRequestMethod("GET");
      }

      postInputStream = postUrlConnection.getInputStream();

      jsonString = readStream(postInputStream);

      return jsonString;

    } catch (IOException e) {
      e.printStackTrace();
      // IF THE SERVER RETURN ERROR THROW EXCEPTION
      try {
        if (postUrlConnection.getResponseCode() == 400) {
          InputStream postInputStream = postUrlConnection.getErrorStream();
          jsonString = readStream(postInputStream);
          Message msg = new Gson().fromJson(jsonString, Message.class);
          throw new ApiCallException(msg.getMessage(), msg.getMessageID());
        }
        DebugUtility.showLog("RESPONSE CODE " + postUrlConnection.getResponseCode());
      } catch (IOException e1) {
        throw new ApiCallException();
      }
      return "{\"messageID\":0,\"message\":\"ERROR\",\"kind\":\"message\"}";
    } finally {
      if (postInputStream != null)
        try {
          postInputStream.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
    }
  }