Example usage for java.net HttpURLConnection HTTP_OK

List of usage examples for java.net HttpURLConnection HTTP_OK

Introduction

In this page you can find the example usage for java.net HttpURLConnection HTTP_OK.

Prototype

int HTTP_OK

To view the source code for java.net HttpURLConnection HTTP_OK.

Click Source Link

Document

HTTP Status-Code 200: OK.

Usage

From source file:com.streamsets.datacollector.updatechecker.UpdateChecker.java

@Override
public void run() {
    updateInfo = null;//from   w w w .j a  v  a  2  s  .c  o m
    PipelineState ps;
    try {
        ps = runner.getState();
    } catch (PipelineStoreException e) {
        LOG.warn(Utils.format("Cannot get pipeline state: '{}'", e.toString()), e);
        return;
    }
    if (ps.getStatus() == PipelineStatus.RUNNING) {
        if (url != null) {
            Map uploadInfo = getUploadInfo();
            if (uploadInfo != null) {
                HttpURLConnection conn = null;
                try {
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(2000);
                    conn.setReadTimeout(2000);
                    conn.setDoOutput(true);
                    conn.setDoInput(true);
                    conn.setRequestProperty("content-type", APPLICATION_JSON_MIME);
                    ObjectMapperFactory.getOneLine().writeValue(conn.getOutputStream(), uploadInfo);
                    if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                        String responseContentType = conn.getHeaderField("content-type");
                        if (APPLICATION_JSON_MIME.equals(responseContentType)) {
                            updateInfo = ObjectMapperFactory.get().readValue(conn.getInputStream(), Map.class);
                        } else {
                            LOG.trace("Got invalid content-type '{}' from from update-check server",
                                    responseContentType);
                        }
                    } else {
                        LOG.trace("Got '{} : {}' from update-check server", conn.getResponseCode(),
                                conn.getResponseMessage());
                    }
                } catch (Exception ex) {
                    LOG.trace("Could not do an update check: {}", ex.toString(), ex);
                } finally {
                    if (conn != null) {
                        conn.disconnect();
                    }
                }
            }
        }
    }
}

From source file:org.apache.calcite.avatica.remote.AvaticaCommonsHttpClientSpnegoImpl.java

@Override
public byte[] send(byte[] request) {
    HttpClientContext context = HttpClientContext.create();

    context.setTargetHost(host);/* w  w  w .j  a  v a2 s .co  m*/
    context.setCredentialsProvider(credentialsProvider);
    context.setAuthSchemeRegistry(authRegistry);
    context.setAuthCache(authCache);

    ByteArrayEntity entity = new ByteArrayEntity(request, ContentType.APPLICATION_OCTET_STREAM);

    // Create the client with the AuthSchemeRegistry and manager
    HttpPost post = new HttpPost(toURI(url));
    post.setEntity(entity);

    try (CloseableHttpResponse response = client.execute(post, context)) {
        final int statusCode = response.getStatusLine().getStatusCode();
        if (HttpURLConnection.HTTP_OK == statusCode || HttpURLConnection.HTTP_INTERNAL_ERROR == statusCode) {
            return EntityUtils.toByteArray(response.getEntity());
        }

        throw new RuntimeException("Failed to execute HTTP Request, got HTTP/" + statusCode);
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        LOG.debug("Failed to execute HTTP request", e);
        throw new RuntimeException(e);
    }
}

From source file:com.murrayc.galaxyzoo.app.provider.client.ZooniverseClient.java

public LoginUtils.LoginResult loginSync(final String username, final String password) throws LoginException {
    HttpUtils.throwIfNoNetwork(getContext(), false); //Ignore the wifi-only setting because this will be when the user is explicitly requesting a login.

    final HttpURLConnection conn;
    try {//  www .ja v  a  2  s  . co m
        conn = openConnection(getLoginUri());
    } catch (final IOException e) {
        Log.error("loginSync(): Could not open connection", e);

        throw new LoginException("Could not open connection.", e);
    }

    final List<NameValuePair> nameValuePairs = new ArrayList<>();
    nameValuePairs.add(new BasicNameValuePair("username", username));
    nameValuePairs.add(new BasicNameValuePair("password", password));

    try {
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);

        writeParamsToHttpPost(conn, nameValuePairs);

        conn.connect();
    } catch (final IOException e) {
        Log.error("loginSync(): exception during HTTP connection", e);

        throw new LoginException("Could not create POST.", e);
    }

    //Get the response:
    InputStream in = null;
    try {
        in = conn.getInputStream();
        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            Log.error("loginSync(): response code: " + conn.getResponseCode());
            return null;
        }

        return LoginUtils.parseLoginResponseContent(in);
    } catch (final IOException e) {
        Log.error("loginSync(): exception during HTTP connection", e);

        throw new LoginException("Could not parse response.", e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (final IOException e) {
                Log.error("loginSync(): exception while closing in", e);
            }
        }
    }
}

From source file:OCRRestAPI.java

private static void DownloadConvertedFile(String outputFileUrl) throws IOException {
    URL downloadUrl = new URL(outputFileUrl);
    HttpURLConnection downloadConnection = (HttpURLConnection) downloadUrl.openConnection();

    if (downloadConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {

        InputStream inputStream = downloadConnection.getInputStream();

        // opens an output stream to save into file
        FileOutputStream outputStream = new FileOutputStream("C:\\converted_file.doc");

        int bytesRead = -1;
        byte[] buffer = new byte[4096];
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }/*w  w  w.  j  av  a 2s . com*/

        outputStream.close();
        inputStream.close();
    }

    downloadConnection.disconnect();
}

From source file:com.box.androidlib.FileTransfer.BoxFileDownload.java

/**
 * Execute a file download./*from   ww  w.ja v a  2s .co m*/
 * 
 * @param fileId
 *            The file_id of the file to be downloaded
 * @param destinationFile
 *            A java.io.File resource to which the downloaded file will be written. Ensure that this points to a valid file-path that can be written to.
 * @param versionId
 *            The version_id of the version of the file to download. Set to null to download the latest version of the file.
 * @return a response handler
 * @throws IOException
 *             Can be thrown if there was a connection error, or if destination file could not be written.
 */
public DefaultResponseParser execute(final long fileId, final File destinationFile, final Long versionId)
        throws IOException {

    final DefaultResponseParser handler = new DefaultResponseParser();

    final Uri.Builder builder = new Uri.Builder();
    builder.scheme(BoxConfig.getInstance().getDownloadUrlScheme());
    builder.authority(BoxConfig.getInstance().getDownloadUrlAuthority());
    builder.path(BoxConfig.getInstance().getDownloadUrlPath());
    builder.appendPath(mAuthToken);
    builder.appendPath(String.valueOf(fileId));
    if (versionId != null) {
        builder.appendPath(String.valueOf(versionId));
    }

    // We normally prefer to use HttpUrlConnection, however that appears to fail
    // for certain types of files. For downloads, it appears DefaultHttpClient works
    // more reliably.
    final DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpGet httpGet;
    try {
        httpGet = new HttpGet(new URI(builder.build().toString()));
    } catch (URISyntaxException e) {
        throw new IOException("Invalid Download URL");
    }
    HttpResponse httpResponse = httpclient.execute(httpGet);
    InputStream is = httpResponse.getEntity().getContent();
    int responseCode = httpResponse.getStatusLine().getStatusCode();

    if (responseCode == HttpURLConnection.HTTP_OK) {
        final FileOutputStream fos = new FileOutputStream(destinationFile);
        final byte[] buffer = new byte[DOWNLOAD_BUFFER_SIZE];
        int bufferLength = 0;
        mBytesTransferred = 0;
        long lastOnProgressPost = 0;
        while ((bufferLength = is.read(buffer)) > 0 && !Thread.currentThread().isInterrupted()) {
            fos.write(buffer, 0, bufferLength);
            mBytesTransferred += bufferLength;
            long currTime = SystemClock.uptimeMillis();
            if (mListener != null && mHandler != null
                    && currTime - lastOnProgressPost > ON_PROGRESS_UPDATE_THRESHOLD) {
                lastOnProgressPost = currTime;
                mHandler.post(mOnProgressRunnable);
            }
        }
        mHandler.post(mOnProgressRunnable);
        fos.close();
        handler.setStatus(FileDownloadListener.STATUS_DOWNLOAD_OK);

        // If download thread was interrupted, set to STATUS_DOWNLOAD_CANCELED
        if (Thread.currentThread().isInterrupted()) {
            handler.setStatus(FileDownloadListener.STATUS_DOWNLOAD_CANCELLED);
        }
        // Even if download completed, Box API may have put an error message
        // in the file itself. Refer to
        // http://developers.box.net/w/page/12923951/ApiFunction_Upload-and-Download
        else if (destinationFile.length() < FILE_ERROR_SIZE) {
            final byte[] buff = new byte[(int) destinationFile.length()];
            final FileInputStream fis = new FileInputStream(destinationFile);
            fis.read(buffer);
            final String str = new String(buff).trim();
            if (str.equals(FileDownloadListener.STATUS_DOWNLOAD_WRONG_AUTH_TOKEN)) {
                handler.setStatus(FileDownloadListener.STATUS_DOWNLOAD_WRONG_AUTH_TOKEN);
            } else if (str.equals(FileDownloadListener.STATUS_DOWNLOAD_RESTRICTED)) {
                handler.setStatus(FileDownloadListener.STATUS_DOWNLOAD_RESTRICTED);
            }
        }
    } else if (responseCode == HttpURLConnection.HTTP_FORBIDDEN) {
        handler.setStatus(FileDownloadListener.STATUS_DOWNLOAD_PERMISSIONS_ERROR);
    } else {
        handler.setStatus(FileDownloadListener.STATUS_DOWNLOAD_FAIL);
    }

    is.close();

    return handler;
}

From source file:net.sf.okapi.filters.drupal.DrupalConnector.java

public Node getNode(String nodeId) {
    try {//ww w .ja  v  a  2s  .  c  o m
        URL url = new URL(host + String.format("rest/node/%s", nodeId));
        HttpURLConnection conn = createConnection(url, "GET", false);

        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            conn.disconnect();
            throw new RuntimeException("Error in getNode(): " + conn.getResponseMessage());
        }

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

        JSONParser parser = new JSONParser();
        JSONObject node = (JSONObject) parser.parse(reader);

        conn.disconnect();

        return new Node(node);
    } catch (Throwable e) {
        throw new RuntimeException("Error in getNode(): " + e.getMessage(), e);
    }
}

From source file:org.sdr.webrec.core.WebRec.java

public void run() {

    initParameters();/*ww w. j  a  v  a 2  s. c om*/

    String transactionName = "";
    HttpResponse response = null;

    DecimalFormat formatter = new DecimalFormat("#####0.00");
    DecimalFormatSymbols dfs = formatter.getDecimalFormatSymbols();
    formatter.setMinimumFractionDigits(3);
    formatter.setMaximumFractionDigits(3);

    // make sure delimeter is a '.' instead of locale default ','
    dfs.setDecimalSeparator('.');
    formatter.setDecimalFormatSymbols(dfs);

    do {
        t1 = System.currentTimeMillis();
        URL siteURL = null;
        try {

            for (int i = 0; i < url.length; i++) {

                LOGGER.debug("url:" + ((Transaction) url[i]).getUrl());

                Transaction transaction = (Transaction) url[i];
                siteURL = new URL(transaction.getUrl());
                transactionName = transaction.getName();

                //if transaction requires server authentication
                if (transaction.isAutenticate())
                    httpclient.getCredentialsProvider().setCredentials(
                            new AuthScope(siteURL.getHost(), siteURL.getPort()),
                            new UsernamePasswordCredentials(transaction.getWorkload().getUsername(),
                                    transaction.getWorkload().getPassword()));

                // Get HTTP GET method
                httpget = new HttpGet(((Transaction) url[i]).getUrl());

                double startTime = System.nanoTime();

                double endTime = 0.00d;

                response = null;

                // Execute HTTP GET
                try {
                    response = httpclient.execute(httpget);
                    endTime = System.nanoTime();

                } catch (Exception e) {
                    httpget.abort();
                    LOGGER.error("ERROR in receiving response:" + e.getLocalizedMessage());
                    e.printStackTrace();
                }

                double timeLapse = 0;

                if (response != null) {
                    if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {

                        timeLapse = endTime - startTime;

                        LOGGER.debug("starttime:" + (new Double(startTime)).toString());
                        LOGGER.debug("timeLapse:" + endTime);
                        LOGGER.debug("timeLapse:" + timeLapse);

                        //move nanos to millis
                        timeLapse = timeLapse / 1000000L;
                        LOGGER.debug("response time:" + formatter.format(timeLapse) + "ms.");
                        out.write(System.currentTimeMillis() / 1000 + ":");
                        out.write(
                                threadName + '.' + transactionName + ":" + formatter.format(timeLapse) + "\n");

                        //content must be consumed just because 
                        //otherwice apache httpconnectionmanager does not release connection back to pool
                        HttpEntity entity = response.getEntity();
                        if (entity != null) {
                            EntityUtils.toByteArray(entity);
                        }

                    } else {
                        LOGGER.error("Status code of transaction:" + transactionName + " was not "
                                + HttpURLConnection.HTTP_OK + " but "
                                + response.getStatusLine().getStatusCode());
                    }

                }
                int sleepTime = delay;
                try {
                    LOGGER.debug("Sleeping " + delay / 1000 + "s...");
                    sleep(sleepTime);
                } catch (InterruptedException ie) {
                    LOGGER.error("ERROR:" + ie);
                    ie.printStackTrace();
                }
            }
        } catch (Exception e) {
            LOGGER.error("Error in thread " + threadName + " with url:" + siteURL + " " + e.getMessage());
            e.printStackTrace();
        }
        try {
            out.flush();
            t2 = System.currentTimeMillis();
            tTask = t2 - t1;

            LOGGER.debug("Total time consumed:" + tTask / 1000 + "s.");

            if (tTask <= interval) {
                //when task takes less than preset time
                LOGGER.debug("Sleeping interval:" + (interval - tTask) / 1000 + "s.");
                sleep(interval - tTask);
            }

            cm.closeExpiredConnections();
        } catch (InterruptedException ie) {
            LOGGER.error("Error:" + ie);
            ie.printStackTrace();
        } catch (Exception e) {
            LOGGER.error("Error:" + e);
            e.printStackTrace();
        }
    } while (true);
}

From source file:de.ub0r.android.websms.connector.freenet.ConnectorFreenet.java

/**
 * send xml command send to freenet XML sms connector and return XML
 * response//from  ww w.j a  v a 2 s  . co  m
 * 
 * @param context
 *            sms connector context
 * @param xml
 *            command to send to freenet XML sms connector
 * @return String contaning XML response
 */
private String sendXml(final Context context, final String xml) {
    String resXml = null;
    try {
        // POST UTF-8 xml command to server
        final HttpPost req = new HttpPost(URL_EMO);
        req.setHeader("content-type", "text/xml");
        final byte[] bytes = xml.getBytes("utf-8");
        req.setEntity(new ByteArrayEntity(bytes));
        final HttpResponse response = this.client.execute(req);
        // check server status
        final int resp = response.getStatusLine().getStatusCode();
        if (resp != HttpURLConnection.HTTP_OK) {
            throw new WebSMSException(context, R.string.error_http, " " + resp);
        }
        // parse XML response into HashMap
        final InputStream in = response.getEntity().getContent();
        final int cnt = in.read(this.httpBuffer);
        if (cnt > 0) {
            resXml = new String(this.httpBuffer, 0, cnt, "utf-8");
        }
        if (null == resXml) {
            throw new WebSMSException(context, R.string.error_http, "no XML from server");
        }
        // else {
        // Log.d(TAG, resXml);
        // }
    } catch (Exception e) {
        Log.e(TAG, "sendXml", e);
        throw new WebSMSException(e.getMessage());
    }
    return resXml;
}