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.scvngr.levelup.core.net.LevelUpResponseTest.java

/**
 * Tests {@link LevelUpResponse#mapStatus(int, String)} with a sub-200 response code.
 *//*ww w .j av  a  2 s . c  om*/
@SmallTest
public void testMapStatusHttp_okCode_notFromPlatform() {
    assertEquals(LevelUpStatus.OK,
            LevelUpResponse.mapStatus(HttpURLConnection.HTTP_OK, SERVER_NOT_LEVELUP_PLATFORM));
}

From source file:de.schildbach.wallet.ui.send.RequestWalletBalanceTask.java

public void requestWalletBalance(final Address... addresses) {
    backgroundHandler.post(new Runnable() {
        @Override//from w w w  .j ava 2 s . c om
        public void run() {
            final StringBuilder url = new StringBuilder(Constants.BITEASY_API_URL);
            url.append("unspent-outputs");
            url.append("?per_page=MAX");
            for (final Address address : addresses)
                url.append("&address[]=").append(address.toString());

            log.debug("trying to request wallet balance from {}", url);

            HttpURLConnection connection = null;
            Reader reader = null;

            try {
                connection = (HttpURLConnection) new URL(url.toString()).openConnection();

                connection.setInstanceFollowRedirects(false);
                connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
                connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
                connection.setUseCaches(false);
                connection.setDoInput(true);
                connection.setDoOutput(false);

                connection.setRequestMethod("GET");
                if (userAgent != null)
                    connection.addRequestProperty("User-Agent", userAgent);
                connection.connect();

                final int responseCode = connection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024),
                            Charsets.UTF_8);
                    final StringBuilder content = new StringBuilder();
                    Io.copy(reader, content);

                    final JSONObject json = new JSONObject(content.toString());

                    final int status = json.getInt("status");
                    if (status != 200)
                        throw new IOException("api status " + status + " when fetching unspent outputs");

                    final JSONObject jsonData = json.getJSONObject("data");

                    final JSONObject jsonPagination = jsonData.getJSONObject("pagination");

                    if (!"false".equals(jsonPagination.getString("next_page")))
                        throw new IllegalStateException("result set too big");

                    final JSONArray jsonOutputs = jsonData.getJSONArray("outputs");

                    final Map<Sha256Hash, Transaction> transactions = new HashMap<Sha256Hash, Transaction>(
                            jsonOutputs.length());

                    for (int i = 0; i < jsonOutputs.length(); i++) {
                        final JSONObject jsonOutput = jsonOutputs.getJSONObject(i);

                        if (jsonOutput.getInt("is_spent") != 0)
                            throw new IllegalStateException("UXTO not spent");

                        final Sha256Hash uxtoHash = new Sha256Hash(jsonOutput.getString("transaction_hash"));
                        final int uxtoIndex = jsonOutput.getInt("transaction_index");
                        final byte[] uxtoScriptBytes = HEX.decode(jsonOutput.getString("script_pub_key"));
                        final Coin uxtoValue = Coin.valueOf(Long.parseLong(jsonOutput.getString("value")));

                        Transaction tx = transactions.get(uxtoHash);
                        if (tx == null) {
                            tx = new FakeTransaction(Constants.NETWORK_PARAMETERS, uxtoHash);
                            tx.getConfidence().setConfidenceType(ConfidenceType.BUILDING);
                            transactions.put(uxtoHash, tx);
                        }

                        if (tx.getOutputs().size() > uxtoIndex)
                            throw new IllegalStateException("cannot reach index " + uxtoIndex
                                    + ", tx already has " + tx.getOutputs().size() + " outputs");

                        // fill with dummies
                        while (tx.getOutputs().size() < uxtoIndex)
                            tx.addOutput(new TransactionOutput(Constants.NETWORK_PARAMETERS, tx,
                                    Coin.NEGATIVE_SATOSHI, new byte[] {}));

                        // add the real output
                        final TransactionOutput output = new TransactionOutput(Constants.NETWORK_PARAMETERS, tx,
                                uxtoValue, uxtoScriptBytes);
                        tx.addOutput(output);
                    }

                    log.info("fetched unspent outputs from {}", url);

                    onResult(transactions.values());
                } else {
                    final String responseMessage = connection.getResponseMessage();

                    log.info("got http error '{}: {}' from {}", responseCode, responseMessage, url);

                    onFail(R.string.error_http, responseCode, responseMessage);
                }
            } catch (final JSONException x) {
                log.info("problem parsing json from " + url, x);

                onFail(R.string.error_parse, x.getMessage());
            } catch (final IOException x) {
                log.info("problem querying unspent outputs from " + url, x);

                onFail(R.string.error_io, x.getMessage());
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (final IOException x) {
                        // swallow
                    }
                }

                if (connection != null)
                    connection.disconnect();
            }
        }
    });
}

From source file:net.joala.expression.library.net.UriStatusCodeExpressionTest.java

@Test(expected = ExpressionEvaluationException.class)
public void get_should_signal_retry_after_timeout() throws Exception {
    webservice.getHttpHandler()/*w ww  .  j a  v a  2  s  . com*/
            .feedResponses(delay(TIMED_OUT_RESPONSE_DELAY_MILLIS, statusCode(HttpURLConnection.HTTP_OK)));
    new UriStatusCodeExpression(FAST_TIMEOUT, webservice.getClientUri()).get();
}

From source file:com.none.tom.simplerssreader.net.FeedDownloader.java

@SuppressWarnings("ConstantConditions")
public static InputStream getInputStream(final Context context, final String feedUrl) {
    final ConnectivityManager manager = context.getSystemService(ConnectivityManager.class);
    final NetworkInfo info = manager.getActiveNetworkInfo();

    if (info == null || !info.isConnected()) {
        ErrorHandler.setErrno(ErrorHandler.ERROR_NETWORK);
        LogUtils.logError("No network connection");
        return null;
    }/*ww w  . j a v a  2s.c o  m*/

    URL url;
    try {
        url = new URL(feedUrl);
    } catch (final MalformedURLException e) {
        ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_BAD_REQUEST, e);
        return null;
    }

    final boolean[] networkPrefs = DefaultSharedPrefUtils.getNetworkPreferences(context);
    final boolean useHttpTorProxy = networkPrefs[0];
    final boolean httpsOnly = networkPrefs[1];
    final boolean followRedir = networkPrefs[2];

    for (int nrRedirects = 0;; nrRedirects++) {
        if (nrRedirects >= HTTP_NR_REDIRECTS_MAX) {
            ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_TOO_MANY_REDIRECTS);
            LogUtils.logError("Too many redirects");
            return null;
        }

        HttpURLConnection conn = null;

        try {
            if (httpsOnly && url.getProtocol().equalsIgnoreCase("http")) {
                ErrorHandler.setErrno(ErrorHandler.ERROR_HTTPS_ONLY);
                LogUtils.logError("Attempting insecure connection");
                return null;
            }

            if (useHttpTorProxy) {
                conn = (HttpURLConnection) url.openConnection(new Proxy(Proxy.Type.HTTP,
                        new InetSocketAddress(InetAddress.getByName(HTTP_PROXY_TOR_IP), HTTP_PROXY_TOR_PORT)));
            } else {
                conn = (HttpURLConnection) url.openConnection();
            }

            conn.setRequestProperty("Accept-Charset", StandardCharsets.UTF_8.name());

            conn.setConnectTimeout(HTTP_URL_DEFAULT_TIMEOUT);
            conn.setReadTimeout(HTTP_URL_DEFAULT_TIMEOUT);

            conn.connect();

            final int responseCode = conn.getResponseCode();

            switch (responseCode) {
            case HttpURLConnection.HTTP_OK:
                return getInputStream(conn.getInputStream());
            case HttpURLConnection.HTTP_MOVED_PERM:
            case HttpURLConnection.HTTP_MOVED_TEMP:
            case HttpURLConnection.HTTP_SEE_OTHER:
            case HTTP_TEMP_REDIRECT:
                if (followRedir) {
                    final String location = conn.getHeaderField("Location");
                    url = new URL(url, location);

                    if (responseCode == HttpURLConnection.HTTP_MOVED_PERM) {
                        SharedPrefUtils.updateSubscriptionUrl(context, url.toString());
                    }
                    continue;
                }
                ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_FOLLOW_REDIRECT_DENIED);
                LogUtils.logError("Couldn't follow redirect");
                return null;
            default:
                if (responseCode < 0) {
                    ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_RESPONSE);
                    LogUtils.logError("No valid HTTP response");
                    return null;
                } else if (responseCode >= 400 && responseCode <= 500) {
                    ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_CLIENT);
                } else if (responseCode >= 500 && responseCode <= 600) {
                    ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_SERVER);
                } else {
                    ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_UNHANDLED);
                }
                LogUtils.logError("Error " + responseCode + ": " + conn.getResponseMessage());
                return null;
            }
        } catch (final IOException e) {
            if ((e instanceof ConnectException && e.getMessage().equals("Network is unreachable"))
                    || e instanceof SocketTimeoutException || e instanceof UnknownHostException) {
                ErrorHandler.setErrno(ErrorHandler.ERROR_NETWORK, e);
            } else {
                ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_UNHANDLED, e);
            }
            return null;
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
    }
}

From source file:ja.ohac.wallet.ui.send.RequestWalletBalanceTask.java

public void requestWalletBalance(final Address... addresses) {
    backgroundHandler.post(new Runnable() {
        @Override/*from www  . j a  v a2 s  .c  om*/
        public void run() {
            final StringBuilder url = new StringBuilder(Constants.BITEASY_API_URL);
            url.append("unspent-outputs");
            url.append("?per_page=MAX");
            for (final Address address : addresses)
                url.append("&address[]=").append(address.toString());

            log.debug("trying to request wallet balance from {}", url);

            HttpURLConnection connection = null;
            Reader reader = null;

            try {
                connection = (HttpURLConnection) new URL(url.toString()).openConnection();

                connection.setInstanceFollowRedirects(false);
                connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
                connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
                connection.setUseCaches(false);
                connection.setDoInput(true);
                connection.setDoOutput(false);

                connection.setRequestMethod("GET");
                if (userAgent != null)
                    connection.addRequestProperty("User-Agent", userAgent);
                connection.connect();

                final int responseCode = connection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024),
                            Charsets.UTF_8);
                    final StringBuilder content = new StringBuilder();
                    Io.copy(reader, content);

                    final JSONObject json = new JSONObject(content.toString());

                    final int status = json.getInt("status");
                    if (status != 200)
                        throw new IOException("api status " + status + " when fetching unspent outputs");

                    final JSONObject jsonData = json.getJSONObject("data");

                    final JSONObject jsonPagination = jsonData.getJSONObject("pagination");

                    if (!"false".equals(jsonPagination.getString("next_page")))
                        throw new IllegalStateException("result set too big");

                    final JSONArray jsonOutputs = jsonData.getJSONArray("outputs");

                    final Map<Sha256Hash, Transaction> transactions = new HashMap<Sha256Hash, Transaction>(
                            jsonOutputs.length());

                    for (int i = 0; i < jsonOutputs.length(); i++) {
                        final JSONObject jsonOutput = jsonOutputs.getJSONObject(i);

                        if (jsonOutput.getInt("is_spent") != 0)
                            throw new IllegalStateException("UXTO not spent");

                        final Sha256Hash uxtoHash = new Sha256Hash(jsonOutput.getString("transaction_hash"));
                        final int uxtoIndex = jsonOutput.getInt("transaction_index");
                        final byte[] uxtoScriptBytes = BaseEncoding.base16().lowerCase()
                                .decode(jsonOutput.getString("script_pub_key"));
                        final BigInteger uxtoValue = new BigInteger(jsonOutput.getString("value"));

                        Transaction tx = transactions.get(uxtoHash);
                        if (tx == null) {
                            tx = new FakeTransaction(Constants.NETWORK_PARAMETERS, uxtoHash);
                            tx.getConfidence().setConfidenceType(ConfidenceType.BUILDING);
                            transactions.put(uxtoHash, tx);
                        }

                        if (tx.getOutputs().size() > uxtoIndex)
                            throw new IllegalStateException("cannot reach index " + uxtoIndex
                                    + ", tx already has " + tx.getOutputs().size() + " outputs");

                        // fill with dummies
                        while (tx.getOutputs().size() < uxtoIndex)
                            tx.addOutput(new TransactionOutput(Constants.NETWORK_PARAMETERS, tx,
                                    Coin.NEGATIVE_SATOSHI, new byte[] {}));

                        // add the real output
                        final TransactionOutput output = new TransactionOutput(Constants.NETWORK_PARAMETERS, tx,
                                Coin.valueOf(uxtoValue.longValue()), uxtoScriptBytes);
                        tx.addOutput(output);
                    }

                    log.info("fetched unspent outputs from {}", url);

                    onResult(transactions.values());
                } else {
                    final String responseMessage = connection.getResponseMessage();

                    log.info("got http error '{}: {}' from {}", responseCode, responseMessage, url);

                    onFail(R.string.error_http, responseCode, responseMessage);
                }
            } catch (final JSONException x) {
                log.info("problem parsing json from " + url, x);

                onFail(R.string.error_parse, x.getMessage());
            } catch (final IOException x) {
                log.info("problem querying unspent outputs from " + url, x);

                onFail(R.string.error_io, x.getMessage());
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (final IOException x) {
                        // swallow
                    }
                }

                if (connection != null)
                    connection.disconnect();
            }
        }
    });
}

From source file:com.aptana.jira.core.JiraManager.java

/**
 * Logs into JIRA with a username and password.
 * //w  ww . j a v  a  2 s .c om
 * @param username
 *            the username
 * @param password
 *            the password
 * @throws JiraException
 */
public void login(String username, String password) throws JiraException {
    HttpURLConnection connection = null;
    try {
        connection = createConnection(getUserURL(username), username, password);
        int code = connection.getResponseCode();
        if (code == HttpURLConnection.HTTP_OK) {
            this.user = new JiraUser(username, password);
            saveCredentials();
            return;
        }

        if (code == HttpURLConnection.HTTP_UNAUTHORIZED || code == HttpURLConnection.HTTP_FORBIDDEN) {
            throw new JiraException(Messages.JiraManager_BadCredentialsErrMsg);
        }
        throw new JiraException(Messages.JiraManager_UnknownErrMsg);
    } catch (Exception e) {
        throw new JiraException(e.getMessage(), e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:org.hupo.psi.mi.psicquic.registry.PsicquicRegistryStatusChecker.java

private void checkStatus(ServiceType serviceStatus) {
    HttpURLConnection urlConnection = null;
    InputStream contentStream = null;
    InputStream countStream = null;
    try {//from w ww.  ja  va 2 s .  c om

        final URL versionUrl = new URL(serviceStatus.getRestUrl() + "version");
        final URL countURL = new URL(serviceStatus.getRestUrl() + "query/*?format=count");

        urlConnection = (HttpURLConnection) versionUrl.openConnection();
        urlConnection.setConnectTimeout(threadTimeOut * 1000);
        urlConnection.setReadTimeout(threadTimeOut * 1000);

        urlConnection.connect();

        int code = urlConnection.getResponseCode();

        if (HttpURLConnection.HTTP_OK == code) {

            serviceStatus.setActive(true);

            final String version;
            final String strCount;

            //TODO Add a double check to know if the service is active
            // or not add a catch block for the exceptions

            contentStream = (InputStream) urlConnection.getContent();
            version = IOUtils.toString(contentStream);
            serviceStatus.setVersion(version);

            countStream = (InputStream) countURL.getContent();
            strCount = IOUtils.toString(countStream);
            serviceStatus.setCount(Long.valueOf(strCount));
        } else {
            serviceStatus.setActive(false);
        }

    } catch (Throwable e) {
        serviceStatus.setActive(false);
    } finally {
        if (contentStream != null) {
            try {
                contentStream.close();
            } catch (IOException e) {
                log.error("Cannot close psicquic content stream", e);
            }
        }
        if (countStream != null) {
            try {
                countStream.close();
            } catch (IOException e) {
                log.error("Cannot close psicquic count stream", e);
            }
        }
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}

From source file:com.baseproject.volley.toolbox.HurlStack.java

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());/* w  w w .j ava  2  s .c  o m*/
    map.putAll(additionalHeaders);
    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException(Util.buildHttpErrorMsg("failed", -1, "URL blocked by rewriter: " + url));
        }
        url = rewritten;
    }
    URL parsedUrl = new URL(url);
    HttpURLConnection connection = openConnection(parsedUrl, request);
    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    setConnectionParametersForRequest(connection, request);
    // Initialize HttpResponse with data from the HttpURLConnection.
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int responseCode = connection.getResponseCode();
    // if (responseCode == -1) {
    // // -1 is returned by getResponseCode() if the response code could not be retrieved.
    // // Signal to the caller that something was wrong with the connection.
    // throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    // }
    if (responseCode != HttpStatus.SC_NOT_MODIFIED && responseCode != HttpURLConnection.HTTP_OK) {
        InputStream in = null;
        try {
            in = connection.getErrorStream();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (in == null) {
            throw new IOException(Util.buildHttpErrorMsg("failed", responseCode, "unknown"));
        } else {
            throw new IOException(Util.convertStreamToString(in));
        }
    }
    StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(),
            connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromConnection(connection));
    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            if (header.getKey().equals("Set-Cookie")) {
                List<String> cookieValue = header.getValue();
                for (String c : cookieValue) {
                    Header h = new BasicHeader(header.getKey(), c);
                    response.addHeader(h);
                }
            } else {
                Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
                response.addHeader(h);
            }
        }
    }
    return response;
}

From source file:com.skcraft.launcher.util.HttpRequest.java

/**
 * Execute the request.// ww w .jav  a  2  s  . c om
 * <p/>
 * After execution, {@link #close()} should be called.
 *
 * @return this object
 * @throws java.io.IOException on I/O error
 */
public HttpRequest execute() throws IOException {
    boolean successful = false;

    try {
        if (conn != null) {
            throw new IllegalArgumentException("Connection already executed");
        }

        conn = (HttpURLConnection) reformat(url).openConnection();
        conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Java) SKMCLauncher");

        if (body != null) {
            conn.setRequestProperty("Content-Type", contentType);
            conn.setRequestProperty("Content-Length", Integer.toString(body.length));
            conn.setDoInput(true);
        }

        for (Map.Entry<String, String> entry : headers.entrySet()) {
            conn.setRequestProperty(entry.getKey(), entry.getValue());
        }

        conn.setRequestMethod(method);
        conn.setUseCaches(false);
        conn.setDoOutput(true);
        conn.setReadTimeout(READ_TIMEOUT);

        conn.connect();

        if (body != null) {
            DataOutputStream out = new DataOutputStream(conn.getOutputStream());
            out.write(body);
            out.flush();
            out.close();
        }

        inputStream = conn.getResponseCode() == HttpURLConnection.HTTP_OK ? conn.getInputStream()
                : conn.getErrorStream();

        successful = true;
    } finally {
        if (!successful) {
            close();
        }
    }

    return this;
}

From source file:at.ac.tuwien.auto.sewoa.http.HttpRetrieverImpl.java

private byte[] send(HttpClient httpClient, HttpMethod method) {
    try {//from   www .  jav  a  2  s  .  c o m
        int httpResult = httpClient.executeMethod(method);
        if (httpResult != HttpURLConnection.HTTP_OK) {
            LOGGER.warn("cannot post data to url {} -> result: {}.", method.getURI().toString(), httpResult);
            ByteStreams.toByteArray(method.getResponseBodyAsStream());
            throw new IllegalStateException("error code");
        } else {
            return ByteStreams.toByteArray(method.getResponseBodyAsStream());
        }
    } catch (Exception e) {
        LOGGER.warn("cannot post http data to url {} due to {}.", method.toString(), e.getMessage());
        throw new IllegalStateException("could not post data");
    }
}