Example usage for com.squareup.okhttp Response isSuccessful

List of usage examples for com.squareup.okhttp Response isSuccessful

Introduction

In this page you can find the example usage for com.squareup.okhttp Response isSuccessful.

Prototype

public boolean isSuccessful() 

Source Link

Document

Returns true if the code is in [200..300), which means the request was successfully received, understood, and accepted.

Usage

From source file:org.apache.nifi.processors.att.m2x.GetM2XStream.java

License:Apache License

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    final ProcessorLog logger = getLogger();
    final OkHttpClient httpClient = getHttpClient();
    final StateManager stateManager = context.getStateManager();
    final String apiKey = context.getProperty(M2X_API_KEY).getValue();
    final String apiUrl = context.getProperty(M2X_API_URL).getValue();
    final String deviceId = context.getProperty(M2X_DEVICE_ID).getValue();
    final String streamName = context.getProperty(M2X_STREAM_NAME).getValue();
    final String streamType = context.getProperty(M2X_STREAM_TYPE).getValue();
    final String startTime = getLastStartTime(context, stateManager);
    final String streamUrl = getStreamUrl(apiUrl, deviceId, streamName, startTime);

    String responseBody;/*from   w w w.j  a v a2  s. co m*/
    try {
        final Request request = new Request.Builder().url(streamUrl).addHeader("X-M2X-KEY", apiKey).build();
        final Response response = httpClient.newCall(request).execute();

        if (!response.isSuccessful()) {
            logger.error(response.message());
            context.yield();
            return;
        }

        responseBody = response.body().string();
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        context.yield();
        return;
    }

    final ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new JodaModule());
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

    try {
        final M2XStreamValues m2xValues = mapper.readValue(responseBody, M2XStreamValues.class);
        final List<M2XStreamValue> m2xValueList = m2xValues.getValues();

        if (!CollectionUtils.isEmpty(m2xValueList)) {
            for (final M2XStreamValue m2xValue : m2xValueList) {
                final DateTime timestamp = m2xValue.getTimestamp();
                final Object valueObj = m2xValue.getValue();
                final Set<Map.Entry<String, Object>> properties = m2xValue.getAdditionalProperties().entrySet();
                final ByteArrayInputStream bytes = new ByteArrayInputStream(
                        String.valueOf(valueObj).getBytes(StandardCharsets.UTF_8));

                FlowFile newFlowFile = session.create();
                newFlowFile = session.importFrom(bytes, newFlowFile);
                newFlowFile = session.putAttribute(newFlowFile, "m2x.device.id", deviceId);
                newFlowFile = session.putAttribute(newFlowFile, "m2x.stream.name", streamName);
                newFlowFile = session.putAttribute(newFlowFile, "m2x.stream.start",
                        m2xValues.getStart().toString());
                newFlowFile = session.putAttribute(newFlowFile, "m2x.stream.end",
                        m2xValues.getEnd().toString());
                newFlowFile = session.putAttribute(newFlowFile, "m2x.stream.limit",
                        String.valueOf(m2xValues.getLimit()));
                newFlowFile = session.putAttribute(newFlowFile, "m2x.stream.value.timestamp",
                        timestamp.toString());
                newFlowFile = session.putAttribute(newFlowFile, "m2x.stream.value.millis",
                        String.valueOf(timestamp.getMillis()));
                for (final Map.Entry<String, Object> e : properties) {
                    newFlowFile = session.putAttribute(newFlowFile, "m2x.stream.value." + e.getKey(),
                            String.valueOf(e.getValue()));
                }

                session.getProvenanceReporter().create(newFlowFile);
                session.transfer(newFlowFile, REL_SUCCESS);
            }
        }

        setLastStartTime(stateManager, m2xValues.getEnd().toString());
    } catch (Throwable t) {
        logger.error(t.getMessage(), t);
        context.yield();
    }
}

From source file:org.apache.nifi.processors.att.m2x.PutM2XStream.java

License:Apache License

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    final FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;//from w  ww.  ja v  a  2  s .com
    }

    final ProcessorLog logger = getLogger();
    final OkHttpClient httpClient = getHttpClient();
    final StateManager stateManager = context.getStateManager();
    final String apiKey = context.getProperty(M2X_API_KEY).getValue();
    final String apiUrl = context.getProperty(M2X_API_URL).getValue();
    final String deviceId = context.getProperty(M2X_DEVICE_ID).getValue();
    final String streamName = context.getProperty(M2X_STREAM_NAME).getValue();
    final String streamType = context.getProperty(M2X_STREAM_TYPE).getValue();
    final String streamUrl = new StringBuilder().append(apiUrl.replaceAll("/*$", "")).append("/devices/")
            .append(deviceId).append("/streams/").append(streamName).append("/value").toString();

    try {
        final AtomicReference<String> postBodyRef = new AtomicReference<>();
        session.read(flowFile, new InputStreamCallback() {
            @Override
            public void process(InputStream is) {
                try {
                    String timestamp = flowFile.getAttribute("m2x.stream.value.timestamp");
                    if (StringUtils.isEmpty(timestamp)) {
                        timestamp = ISODateTimeFormat.dateTime().print(flowFile.getEntryDate());
                    }
                    final String value = IOUtils.toString(is, StandardCharsets.UTF_8);

                    final M2XStreamValue m2xValue = new M2XStreamValue();
                    m2xValue.setValue(value);
                    m2xValue.setTimestamp(timestamp);

                    final ObjectMapper mapper = new ObjectMapper();
                    mapper.registerModule(new JodaModule());
                    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

                    final String postBody = mapper.writeValueAsString(m2xValue);
                    logger.warn("POST body is {}", new Object[] { postBody });
                    postBodyRef.set(postBody);
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        });

        final String postBody = postBodyRef.get();
        if (StringUtils.isEmpty(postBody)) {
            logger.error("FlowFile {} contents didn't produce a valid M2X stream value",
                    new Object[] { flowFile });
            session.transfer(flowFile, REL_FAILURE);
            return;
        }

        final Request request = new Request.Builder().url(streamUrl).addHeader("X-M2X-KEY", apiKey)
                .put(RequestBody.create(MEDIA_TYPE_JSON, postBody)).build();
        final Response response = httpClient.newCall(request).execute();

        if (!response.isSuccessful()) {
            logger.error(response.message());
            context.yield();
            session.penalize(flowFile);
            return;
        }
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        context.yield();
        session.penalize(flowFile);
        return;
    }

    session.transfer(flowFile, REL_SUCCESS);
}

From source file:org.apache.pulsar.functions.runtime.KubernetesRuntime.java

License:Apache License

public void deleteStatefulSet() throws InterruptedException {
    String statefulSetName = createJobName(instanceConfig.getFunctionDetails());
    final V1DeleteOptions options = new V1DeleteOptions();
    options.setGracePeriodSeconds(5L);/* w w w  .  j av  a 2  s  .  co  m*/
    options.setPropagationPolicy("Foreground");

    String fqfn = FunctionDetailsUtils.getFullyQualifiedName(instanceConfig.getFunctionDetails());
    RuntimeUtils.Actions.Action deleteStatefulSet = RuntimeUtils.Actions.Action.builder()
            .actionName(String.format("Deleting statefulset for function %s", fqfn)).numRetries(NUM_RETRIES)
            .sleepBetweenInvocationsMs(SLEEP_BETWEEN_RETRIES_MS).supplier(() -> {
                Response response;
                try {
                    // cannot use deleteNamespacedStatefulSet because of bug in kuberenetes
                    // https://github.com/kubernetes-client/java/issues/86
                    response = appsClient.deleteNamespacedStatefulSetCall(statefulSetName, jobNamespace,
                            options, null, null, null, null, null, null).execute();
                } catch (ApiException e) {
                    // if already deleted
                    if (e.getCode() == HTTP_NOT_FOUND) {
                        log.warn("Statefulset for function {} does not exist", fqfn);
                        return RuntimeUtils.Actions.ActionResult.builder().success(true).build();
                    }

                    String errorMsg = e.getResponseBody() != null ? e.getResponseBody() : e.getMessage();
                    return RuntimeUtils.Actions.ActionResult.builder().success(false).errorMsg(errorMsg)
                            .build();
                } catch (IOException e) {
                    return RuntimeUtils.Actions.ActionResult.builder().success(false).errorMsg(e.getMessage())
                            .build();
                }

                // if already deleted
                if (response.code() == HTTP_NOT_FOUND) {
                    log.warn("Statefulset for function {} does not exist", fqfn);
                    return RuntimeUtils.Actions.ActionResult.builder().success(true).build();
                } else {
                    return RuntimeUtils.Actions.ActionResult.builder().success(response.isSuccessful())
                            .errorMsg(response.message()).build();
                }
            }).build();

    RuntimeUtils.Actions.Action waitForStatefulSetDeletion = RuntimeUtils.Actions.Action.builder()
            .actionName(String.format("Waiting for statefulset for function %s to complete deletion", fqfn))
            // set retry period to be about 2x the graceshutdown time
            .numRetries(NUM_RETRIES * 2).sleepBetweenInvocationsMs(SLEEP_BETWEEN_RETRIES_MS * 2)
            .supplier(() -> {
                V1StatefulSet response;
                try {
                    response = appsClient.readNamespacedStatefulSet(statefulSetName, jobNamespace, null, null,
                            null);
                } catch (ApiException e) {
                    // statefulset is gone
                    if (e.getCode() == HTTP_NOT_FOUND) {
                        return RuntimeUtils.Actions.ActionResult.builder().success(true).build();
                    }

                    String errorMsg = e.getResponseBody() != null ? e.getResponseBody() : e.getMessage();
                    return RuntimeUtils.Actions.ActionResult.builder().success(false).errorMsg(errorMsg)
                            .build();
                }
                return RuntimeUtils.Actions.ActionResult.builder().success(false)
                        .errorMsg(response.getStatus().toString()).build();
            }).build();

    // Need to wait for all pods to die so we can cleanup subscriptions.
    RuntimeUtils.Actions.Action waitForStatefulPodsToTerminate = RuntimeUtils.Actions.Action.builder()
            .actionName(String.format("Waiting for pods for function %s to terminate", fqfn))
            .numRetries(NUM_RETRIES * 2).sleepBetweenInvocationsMs(SLEEP_BETWEEN_RETRIES_MS * 2)
            .supplier(() -> {
                String labels = String.format("tenant=%s,namespace=%s,name=%s",
                        instanceConfig.getFunctionDetails().getTenant(),
                        instanceConfig.getFunctionDetails().getNamespace(),
                        instanceConfig.getFunctionDetails().getName());

                V1PodList response;
                try {
                    response = coreClient.listNamespacedPod(jobNamespace, null, null, null, null, labels, null,
                            null, null, null);
                } catch (ApiException e) {

                    String errorMsg = e.getResponseBody() != null ? e.getResponseBody() : e.getMessage();
                    return RuntimeUtils.Actions.ActionResult.builder().success(false).errorMsg(errorMsg)
                            .build();
                }

                if (response.getItems().size() > 0) {
                    return RuntimeUtils.Actions.ActionResult.builder().success(false)
                            .errorMsg(response.getItems().size() + " pods still alive.").build();
                } else {
                    return RuntimeUtils.Actions.ActionResult.builder().success(true).build();
                }
            }).build();

    AtomicBoolean success = new AtomicBoolean(false);
    RuntimeUtils.Actions.newBuilder().addAction(deleteStatefulSet.toBuilder().continueOn(true).build())
            .addAction(waitForStatefulSetDeletion.toBuilder().continueOn(false)
                    .onSuccess(() -> success.set(true)).build())
            .addAction(deleteStatefulSet.toBuilder().continueOn(true).build())
            .addAction(waitForStatefulSetDeletion.toBuilder().onSuccess(() -> success.set(true)).build()).run();

    if (!success.get()) {
        throw new RuntimeException(String.format("Failed to delete statefulset for function %s", fqfn));
    } else {
        // wait for pods to terminate
        RuntimeUtils.Actions.newBuilder().addAction(waitForStatefulPodsToTerminate).run();
    }
}

From source file:org.apache.pulsar.functions.runtime.KubernetesRuntime.java

License:Apache License

public void deleteService() throws InterruptedException {

    final V1DeleteOptions options = new V1DeleteOptions();
    options.setGracePeriodSeconds(0L);// w  w w  . ja va2  s  . co  m
    options.setPropagationPolicy("Foreground");
    String fqfn = FunctionDetailsUtils.getFullyQualifiedName(instanceConfig.getFunctionDetails());
    String serviceName = createJobName(instanceConfig.getFunctionDetails());

    RuntimeUtils.Actions.Action deleteService = RuntimeUtils.Actions.Action.builder()
            .actionName(String.format("Deleting service for function %s", fqfn)).numRetries(NUM_RETRIES)
            .sleepBetweenInvocationsMs(SLEEP_BETWEEN_RETRIES_MS).supplier(() -> {
                final Response response;
                try {
                    // cannot use deleteNamespacedService because of bug in kuberenetes
                    // https://github.com/kubernetes-client/java/issues/86
                    response = coreClient.deleteNamespacedServiceCall(serviceName, jobNamespace, options, null,
                            null, null, null, null, null).execute();
                } catch (ApiException e) {
                    // if already deleted
                    if (e.getCode() == HTTP_NOT_FOUND) {
                        log.warn("Service for function {} does not exist", fqfn);
                        return RuntimeUtils.Actions.ActionResult.builder().success(true).build();
                    }

                    String errorMsg = e.getResponseBody() != null ? e.getResponseBody() : e.getMessage();
                    return RuntimeUtils.Actions.ActionResult.builder().success(false).errorMsg(errorMsg)
                            .build();
                } catch (IOException e) {
                    return RuntimeUtils.Actions.ActionResult.builder().success(false).errorMsg(e.getMessage())
                            .build();
                }

                // if already deleted
                if (response.code() == HTTP_NOT_FOUND) {
                    log.warn("Service for function {} does not exist", fqfn);
                    return RuntimeUtils.Actions.ActionResult.builder().success(true).build();
                } else {
                    return RuntimeUtils.Actions.ActionResult.builder().success(response.isSuccessful())
                            .errorMsg(response.message()).build();
                }
            }).build();

    RuntimeUtils.Actions.Action waitForServiceDeletion = RuntimeUtils.Actions.Action.builder()
            .actionName(String.format("Waiting for statefulset for function %s to complete deletion", fqfn))
            .numRetries(NUM_RETRIES).sleepBetweenInvocationsMs(SLEEP_BETWEEN_RETRIES_MS).supplier(() -> {
                V1Service response;
                try {
                    response = coreClient.readNamespacedService(serviceName, jobNamespace, null, null, null);

                } catch (ApiException e) {
                    // statefulset is gone
                    if (e.getCode() == HTTP_NOT_FOUND) {
                        return RuntimeUtils.Actions.ActionResult.builder().success(true).build();
                    }
                    String errorMsg = e.getResponseBody() != null ? e.getResponseBody() : e.getMessage();
                    return RuntimeUtils.Actions.ActionResult.builder().success(false).errorMsg(errorMsg)
                            .build();
                }
                return RuntimeUtils.Actions.ActionResult.builder().success(false)
                        .errorMsg(response.getStatus().toString()).build();
            }).build();

    AtomicBoolean success = new AtomicBoolean(false);
    RuntimeUtils.Actions.newBuilder().addAction(deleteService.toBuilder().continueOn(true).build())
            .addAction(waitForServiceDeletion.toBuilder().continueOn(false).onSuccess(() -> success.set(true))
                    .build())
            .addAction(deleteService.toBuilder().continueOn(true).build())
            .addAction(waitForServiceDeletion.toBuilder().onSuccess(() -> success.set(true)).build()).run();

    if (!success.get()) {
        throw new RuntimeException(String.format("Failed to delete service for function %s", fqfn));
    }
}

From source file:org.bitcoinj_extra.net.discovery.HttpDiscovery.java

License:Apache License

@Override
public InetSocketAddress[] getPeers(long services, long timeoutValue, TimeUnit timeoutUnit)
        throws PeerDiscoveryException {
    try {/*from   w ww  . jav a  2  s .  com*/
        HttpUrl.Builder url = HttpUrl.get(details.uri).newBuilder();
        if (services != 0)
            url.addQueryParameter("srvmask", Long.toString(services));
        Request.Builder request = new Request.Builder();
        request.url(url.build());
        request.addHeader("User-Agent", VersionMessage.LIBRARY_SUBVER); // TODO Add main version.
        log.info("Requesting seeds from {}", url);
        Response response = client.newCall(request.build()).execute();
        if (!response.isSuccessful())
            throw new PeerDiscoveryException(
                    "HTTP request failed: " + response.code() + " " + response.message());
        InputStream stream = response.body().byteStream();
        GZIPInputStream zip = new GZIPInputStream(stream);
        PeerSeedProtos.SignedPeerSeeds proto = PeerSeedProtos.SignedPeerSeeds.parseDelimitedFrom(zip);
        stream.close();
        return protoToAddrs(proto);
    } catch (PeerDiscoveryException e1) {
        throw e1;
    } catch (Exception e) {
        throw new PeerDiscoveryException(e);
    }
}

From source file:org.catrobat.catroid.web.ServerCalls.java

License:Open Source License

public void uploadProject(String projectName, String projectDescription, String zipFileString, String userEmail,
        String language, String token, String username, ResultReceiver receiver, Integer notificationId,
        Context context) throws WebconnectionException {

    Preconditions.checkNotNull(context, "Context cannot be null!");

    userEmail = emailForUiTests == null ? userEmail : emailForUiTests;
    userEmail = userEmail == null ? "" : userEmail;

    try {//from   w  w  w .ja  v  a2  s.co  m
        String md5Checksum = Utils.md5Checksum(new File(zipFileString));

        final String serverUrl = useTestUrl ? TEST_FILE_UPLOAD_URL_HTTP : FILE_UPLOAD_URL;

        Log.v(TAG, "Url to upload: " + serverUrl);

        File file = new File(zipFileString);
        RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM)
                .addFormDataPart(FILE_UPLOAD_TAG, ProjectUploadService.UPLOAD_FILE_NAME,
                        RequestBody.create(MEDIA_TYPE_ZIPFILE, file))
                .addFormDataPart(PROJECT_NAME_TAG, projectName)
                .addFormDataPart(PROJECT_DESCRIPTION_TAG, projectDescription)
                .addFormDataPart(USER_EMAIL, userEmail).addFormDataPart(PROJECT_CHECKSUM_TAG, md5Checksum)
                .addFormDataPart(Constants.TOKEN, token).addFormDataPart(Constants.USERNAME, username)
                .addFormDataPart(DEVICE_LANGUAGE, language).build();

        Request request = new Request.Builder().url(serverUrl).post(requestBody).build();

        Response response = okHttpClient.newCall(request).execute();

        if (response.isSuccessful()) {
            Log.v(TAG, "Upload successful");
            StatusBarNotificationManager.getInstance().showOrUpdateNotification(notificationId, 100);
        } else {
            Log.v(TAG, "Upload not successful");
            throw new WebconnectionException(response.code(),
                    "Upload failed! HTTP Status code was " + response.code());
        }

        UploadResponse uploadResponse = gson.fromJson(response.body().string(), UploadResponse.class);

        String newToken = uploadResponse.token;
        String answer = uploadResponse.answer;
        int status = uploadResponse.statusCode;
        projectId = uploadResponse.projectId;

        if (status != SERVER_RESPONSE_TOKEN_OK) {
            throw new WebconnectionException(status, "Upload failed! JSON Response was " + status);
        }

        if (token.length() != TOKEN_LENGTH || token.isEmpty() || token.equals(TOKEN_CODE_INVALID)) {
            throw new WebconnectionException(status, answer);
        }
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        sharedPreferences.edit().putString(Constants.TOKEN, newToken).commit();
        sharedPreferences.edit().putString(Constants.USERNAME, username).commit();
    } catch (JsonSyntaxException jsonSyntaxException) {
        Log.e(TAG, Log.getStackTraceString(jsonSyntaxException));
        throw new WebconnectionException(WebconnectionException.ERROR_JSON, "JsonSyntaxException");
    } catch (IOException ioException) {
        Log.e(TAG, Log.getStackTraceString(ioException));
        throw new WebconnectionException(WebconnectionException.ERROR_NETWORK, "I/O Exception");
    }
}

From source file:org.dfotos.rssfilter.src.AbstractSrc.java

License:Open Source License

/**
 * Performs the HTTP GET request using the "url" field. Returns the response
 * body or throws the IOException in case the URL can not be retrieved.
 * @return The response body.//from   ww w .  j  av a 2 s .  c o  m
 * @throws IOException Something went wrong.
 */
public final String doHttpGet() throws IOException {
    LOG.log(Level.INFO, "{0}, reading...", new Object[] { getName() });
    if (client == null) {
        client = new OkHttpClient();
    }
    Request request = new Request.Builder().url(url).build();
    Response response = client.newCall(request).execute();
    long respLength = 0;
    if (response.body() != null) {
        respLength = response.body().contentLength();
    }
    if (!response.isSuccessful()) {
        LOG.log(Level.INFO, "HTTP response: " + response + " length: " + respLength);
        throw new IOException("Server error: " + response);
    }
    String tmp = response.body().string();
    LOG.log(Level.FINE, "{0}, {1} bytes read", new Object[] { getName(), tmp.length() });
    return tmp;
}

From source file:org.eyeseetea.malariacare.network.NetworkUtils.java

License:Open Source License

/**
 * Pushes data to DHIS Server/*  w ww .  j a va  2s. c  o m*/
 * @param data
 */
public JSONObject pushData(JSONObject data) throws Exception {
    Response response = null;

    final String DHIS_URL = getDhisURL() + DHIS_PUSH_API;

    OkHttpClient client = UnsafeOkHttpsClientFactory.getUnsafeOkHttpClient();
    client.setConnectTimeout(30, TimeUnit.SECONDS); // connect timeout
    client.setReadTimeout(30, TimeUnit.SECONDS); // socket timeout
    client.setWriteTimeout(30, TimeUnit.SECONDS); // write timeout
    client.setRetryOnConnectionFailure(false); // Cancel retry on failure
    BasicAuthenticator basicAuthenticator = new BasicAuthenticator();
    client.setAuthenticator(basicAuthenticator);

    Log.d(TAG, "Url" + DHIS_URL + "");
    RequestBody body = RequestBody.create(JSON, data.toString());
    Request request = new Request.Builder()
            .header(basicAuthenticator.AUTHORIZATION_HEADER, basicAuthenticator.getCredentials()).url(DHIS_URL)
            .post(body).build();

    response = client.newCall(request).execute();
    if (!response.isSuccessful()) {
        Log.e(TAG, "pushData (" + response.code() + "): " + response.body().string());
        throw new IOException(response.message());
    }
    return parseResponse(response.body().string());
}

From source file:org.eyeseetea.malariacare.network.NetworkUtils.java

License:Open Source License

/**
 * Pull data from DHIS Server//w  w  w .j ava2s .  co  m
 * @param data
 */
public JSONObject getData(String data) throws Exception {
    Response response = null;

    final String DHIS_URL = getDhisURL() + DHIS_PULL_API + data;

    OkHttpClient client = UnsafeOkHttpsClientFactory.getUnsafeOkHttpClient();

    BasicAuthenticator basicAuthenticator = new BasicAuthenticator();
    client.setAuthenticator(basicAuthenticator);

    Log.d(TAG, "Url" + DHIS_URL + "");
    Request request = new Request.Builder()
            .header(basicAuthenticator.AUTHORIZATION_HEADER, basicAuthenticator.getCredentials()).url(DHIS_URL)
            .get().build();

    response = client.newCall(request).execute();
    if (!response.isSuccessful()) {
        Log.e(TAG, "getData (" + response.code() + "): " + response.body().string());
        throw new IOException(response.message());
    }
    return parseResponse(response.body().string());
}

From source file:org.eyeseetea.malariacare.network.PushClient.java

License:Open Source License

/**
 * Pushes data to DHIS Server//w  w  w.  j  av  a  2 s .  c  om
 * @param data
 */
private JSONObject pushData(JSONObject data) throws Exception {
    Response response = null;

    final String DHIS_URL = getDhisURL();

    OkHttpClient client = UnsafeOkHttpsClientFactory.getUnsafeOkHttpClient();

    BasicAuthenticator basicAuthenticator = new BasicAuthenticator();
    client.setAuthenticator(basicAuthenticator);

    RequestBody body = RequestBody.create(JSON, data.toString());
    Request request = new Request.Builder()
            .header(basicAuthenticator.AUTHORIZATION_HEADER, basicAuthenticator.getCredentials()).url(DHIS_URL)
            .post(body).build();

    response = client.newCall(request).execute();
    if (!response.isSuccessful()) {
        Log.e(TAG, "pushData (" + response.code() + "): " + response.body().string());
        throw new IOException(response.message());
    }
    return parseResponse(response.body().string());
}