Example usage for java.net HttpURLConnection getResponseCode

List of usage examples for java.net HttpURLConnection getResponseCode

Introduction

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

Prototype

public int getResponseCode() throws IOException 

Source Link

Document

Gets the status code from an HTTP response message.

Usage

From source file:yodlee.ysl.api.io.HTTP.java

public static String doGet(String url, Map<String, String> sessionTokens)
        throws IOException, URISyntaxException {
    String mn = "doIO(GET :" + url + ", sessionTokens =  " + sessionTokens.toString() + " )";
    System.out.println(fqcn + " :: " + mn);
    URL myURL = new URL(url);
    System.out.println(fqcn + " :: " + mn + ": Request URL=" + url.toString());
    HttpURLConnection conn = (HttpURLConnection) myURL.openConnection();
    //conn.setRequestMethod("GET");
    conn.setRequestProperty("User-Agent", userAgent);
    //conn.setRequestProperty("Content-Type", contentTypeJSON);
    //conn.setRequestProperty("Accept",);
    conn.setRequestProperty("Authorization", sessionTokens.toString());
    conn.setDoOutput(true);/*from w  w w .j a va  2s  .c o m*/
    System.out.println(fqcn + " :: " + mn + " : " + "Sending 'HTTP GET' request");
    int responseCode = conn.getResponseCode();
    System.out.println(fqcn + " :: " + mn + " : " + "Response Code : " + responseCode);
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String inputLine;
    StringBuilder jsonResponse = new StringBuilder();
    while ((inputLine = in.readLine()) != null) {
        System.out.println(inputLine);
        jsonResponse.append(inputLine);
    }
    in.close();
    System.out.println(fqcn + " :: " + mn + " : " + jsonResponse.toString());
    return new String(jsonResponse);
}

From source file:hashengineering.digitalcoin.wallet.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> getBitcoinCharts() {
    try {//ww  w  . j  ava  2s .c o m
        Double btcRate = 0.0;

        Object result = getCoinValueBTC();

        if (result == null)
            return null;

        else
            btcRate = (Double) result;

        final URL URL = new URL("http://api.bitcoincharts.com/v1/weighted_prices.json");
        final HttpURLConnection connection = (HttpURLConnection) URL.openConnection();
        connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.connect();

        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
            return null;

        Reader reader = null;
        try {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024),
                    Constants.UTF_8);
            final StringBuilder content = new StringBuilder();
            Io.copy(reader, content);

            final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();

            //Add Bitcoin information
            rates.put(CoinDefinition.cryptsyMarketCurrency,
                    new ExchangeRate(CoinDefinition.cryptsyMarketCurrency,
                            Utils.toNanoCoins(String.format("%.8f", btcRate).replace(",", ".")),
                            "pubapi.cryptsy.com"));

            final JSONObject head = new JSONObject(content.toString());
            for (final Iterator<String> i = head.keys(); i.hasNext();) {
                final String currencyCode = i.next();
                if (!"timestamp".equals(currencyCode)) {
                    final JSONObject o = head.getJSONObject(currencyCode);
                    String rate = o.optString("24h", null);
                    if (rate == null)
                        rate = o.optString("7d", null);
                    if (rate == null)
                        rate = o.optString("30d", null);

                    double rateForBTC = Double.parseDouble(rate);

                    rate = String.format("%.8f", rateForBTC * btcRate);

                    if (rate != null) {
                        try {
                            rates.put(currencyCode, new ExchangeRate(currencyCode,
                                    Utils.toNanoCoins(rate.replace(",", ".")), URL.getHost()));
                        } catch (final ArithmeticException x) {
                            log.debug("problem reading exchange rate: " + currencyCode, x);
                        }
                    }
                }
            }

            return rates;
        } finally {
            if (reader != null)
                reader.close();
        }
    } catch (final Exception x) {
        log.debug("problem reading exchange rates", x);
    }

    return null;
}

From source file:Main.java

public static boolean downloadFile(File file, URL url) throws IOException {
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    HttpURLConnection conn = null;
    try {//ww  w.ja va2 s. com
        conn = (HttpURLConnection) url.openConnection();
        bis = new BufferedInputStream(conn.getInputStream());
        bos = new BufferedOutputStream(new FileOutputStream(file));

        int contentLength = conn.getContentLength();

        byte[] buffer = new byte[BUFFER_SIZE];
        int read = 0;
        int count = 0;
        while ((read = bis.read(buffer)) != -1) {
            bos.write(buffer, 0, read);
            count += read;
        }
        if (count < contentLength)
            return false;
        int responseCode = conn.getResponseCode();
        if (responseCode / 100 != 2) {
            // error
            return false;
        }
        // finished
        return true;
    } finally {
        try {
            bis.close();
            bos.close();
            conn.disconnect();
        } catch (Exception e) {
        }
    }
}

From source file:Main.java

static byte[] httpRequest(String url, byte[] requestBytes, int connectionTimeOutMs, int readTimeOutMs) {
    byte[] bArr = null;
    if (!(url == null || requestBytes == null)) {
        InputStream inputStream = null;
        HttpURLConnection urlConnection = null;
        try {//from w  ww  . j ava 2s . c om
            urlConnection = (HttpURLConnection) new URL(url).openConnection();
            urlConnection.setDoOutput(true);
            urlConnection.setConnectTimeout(connectionTimeOutMs);
            urlConnection.setReadTimeout(readTimeOutMs);
            urlConnection.setFixedLengthStreamingMode(requestBytes.length);
            OutputStream outputStream = urlConnection.getOutputStream();
            outputStream.write(requestBytes);
            outputStream.close();
            if (urlConnection.getResponseCode() != 200) {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                    }
                }
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
            } else {
                inputStream = urlConnection.getInputStream();
                ByteArrayOutputStream result = new ByteArrayOutputStream();
                byte[] buffer = new byte[16384];
                while (true) {
                    int chunkSize = inputStream.read(buffer);
                    if (chunkSize < 0) {
                        break;
                    } else if (chunkSize > 0) {
                        result.write(buffer, 0, chunkSize);
                    }
                }
                bArr = result.toByteArray();
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e2) {
                    }
                }
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
            }
        } catch (IOException e3) {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e4) {
                }
            }
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        } catch (Throwable th) {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e5) {
                }
            }
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }
    }
    return bArr;
}

From source file:com.memetix.gun4j.GunshortenAPI.java

protected static JSONObject post(final String serviceUrl, final String paramsString) throws Exception {
    final URL url = new URL(serviceUrl);
    final HttpURLConnection uc = (HttpURLConnection) url.openConnection();
    if (referrer != null)
        uc.setRequestProperty("referer", referrer);

    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=" + ENCODING);
    uc.setRequestProperty("Accept-Charset", ENCODING);
    uc.setRequestMethod("POST");
    uc.setDoOutput(true);/*from  ww  w.j  ava2  s. c  om*/

    final PrintWriter pw = new PrintWriter(uc.getOutputStream());
    pw.write(paramsString);
    pw.close();
    uc.getOutputStream().close();

    try {
        final int responseCode = uc.getResponseCode();
        final String result = inputStreamToString(uc.getInputStream());
        if (responseCode != 200) {
            throw new Exception("Error from Gunshorten API: " + result);
        }
        return parseJSON(result);
    } finally {
        uc.getInputStream().close();
        if (uc.getErrorStream() != null) {
            uc.getErrorStream().close();
        }
    }
}

From source file:Main.java

/**
 * Issue a POST request to the server./* ww w  .ja  v a2s  .  com*/
 *
 * @param endpoint
 *            POST address.
 * @param params
 *            request parameters.
 *
 * @throws java.io.IOException
 *             propagated from POST.
 */
public static String post(String endpoint, Map<String, String> params) throws IOException {
    URL url;
    try {
        url = new URL(endpoint);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("invalid url: " + endpoint);
    }
    StringBuilder bodyBuilder = new StringBuilder();
    Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
    // constructs the POST body using the parameters
    while (iterator.hasNext()) {
        Entry<String, String> param = iterator.next();
        bodyBuilder.append(param.getKey()).append('=').append(param.getValue());
        if (iterator.hasNext()) {
            bodyBuilder.append('&');
        }
    }
    String body = bodyBuilder.toString();
    byte[] bytes = body.getBytes();
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setFixedLengthStreamingMode(bytes.length);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        // post the request
        OutputStream out = conn.getOutputStream();
        out.write(bytes);
        out.close();
        // handle the response
        int status = conn.getResponseCode();
        if (status != 200) {
            throw new IOException("Post failed with error code " + status);
        }

        // Get Response
        InputStream is = conn.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\n');
        }
        rd.close();
        return response.toString();

    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:loadTest.loadTestLib.LUtil.java

public static boolean startDockerBuild() throws IOException, InterruptedException {
    if (useDocker) {
        if (runInDockerCluster) {

            HashMap<String, Integer> dockerNodes = getDockerNodes();
            String dockerTar = LUtil.class.getClassLoader().getResource("docker/loadTest.tar").toString()
                    .substring(5);/*from  w w w  . j  a  va2s . c  om*/
            ExecutorService exec = Executors.newFixedThreadPool(dockerNodes.size());

            dockerError = false;
            doneDockers = 0;

            for (Entry<String, Integer> entry : dockerNodes.entrySet()) {
                exec.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String url = entry.getKey() + "/images/vauvenal5/loadtest";
                            URL obj = new URL(url);
                            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
                            con.setRequestMethod("DELETE");
                            con.setRequestProperty("force", "true");
                            int responseCode = con.getResponseCode();
                            con.disconnect();

                            url = entry.getKey()
                                    + "/build?t=vauvenal5/loadtest&dockerfile=./loadTest/Dockerfile";
                            obj = new URL(url);
                            con = (HttpURLConnection) obj.openConnection();
                            con.setRequestMethod("POST");
                            con.setRequestProperty("Content-type", "application/tar");
                            con.setDoOutput(true);
                            File file = new File(dockerTar);
                            FileInputStream fileStr = new FileInputStream(file);
                            byte[] b = new byte[(int) file.length()];
                            fileStr.read(b);
                            con.getOutputStream().write(b);
                            con.getOutputStream().flush();
                            con.getOutputStream().close();

                            responseCode = con.getResponseCode();

                            if (responseCode != 200) {
                                dockerError = true;
                            }

                            String msg = "";

                            do {
                                Thread.sleep(5000);
                                msg = "";
                                url = entry.getKey() + "/images/json";
                                obj = new URL(url);
                                HttpURLConnection con2 = (HttpURLConnection) obj.openConnection();
                                con2.setRequestMethod("GET");
                                responseCode = con2.getResponseCode();

                                BufferedReader in = new BufferedReader(
                                        new InputStreamReader(con2.getInputStream()));
                                String line = null;

                                while ((line = in.readLine()) != null) {
                                    msg += line;
                                }

                                con2.disconnect();
                            } while (!msg.contains("vauvenal5/loadtest"));

                            con.disconnect();
                            doneDockers++;
                        } catch (MalformedURLException ex) {
                            dockerError = true;
                        } catch (FileNotFoundException ex) {
                            dockerError = true;
                        } catch (IOException ex) {
                            dockerError = true;
                        } catch (InterruptedException ex) {
                            dockerError = true;
                        }
                    }
                });
            }

            while (doneDockers < dockerNodes.size()) {
                Thread.sleep(5000);
            }

            return !dockerError;
        }

        //get the path and substring the 'file:' from the URI
        String dockerfile = LUtil.class.getClassLoader().getResource("docker/loadTest").toString().substring(5);

        ProcessBuilder processBuilder = new ProcessBuilder("docker", "rmi", "-f", "vauvenal5/loadtest");
        processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
        Process docker = processBuilder.start();

        docker.waitFor();

        processBuilder = new ProcessBuilder("docker", "build", "-t", "vauvenal5/loadtest", dockerfile);
        processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
        Process proc = processBuilder.start();
        return proc.waitFor() == 0;
    }
    return true;
}

From source file:com.example.android.didyoufeelit.Utils.java

/**
 * Make an HTTP request to the given URL and return a String as the response.
 *//*from  w  w w.  j av  a 2  s .  co  m*/
private static String makeHttpRequest(URL url) throws IOException {
    String jsonResponse = "";

    // If the URL is null, then return early.
    if (url == null) {
        return jsonResponse;
    }

    HttpURLConnection urlConnection = null;
    InputStream inputStream = null;
    try {
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setReadTimeout(10000 /* milliseconds */);
        urlConnection.setConnectTimeout(15000 /* milliseconds */);
        urlConnection.setRequestMethod("GET");
        urlConnection.connect();

        // If the request was successful (response code 200),
        // then read the input stream and parse the response.
        if (urlConnection.getResponseCode() == 200) {
            inputStream = urlConnection.getInputStream();
            jsonResponse = readFromStream(inputStream);
        } else {
            Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
        }
    } catch (IOException e) {
        Log.e(LOG_TAG, "Problem retrieving the earthquake JSON results.", e);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (inputStream != null) {
            inputStream.close();
        }
    }
    return jsonResponse;
}

From source file:yodlee.ysl.api.io.HTTP.java

public static String doPost(String url, String requestBody) throws IOException {
    String mn = "doIO(POST : " + url + ", " + requestBody + " )";
    System.out.println(fqcn + " :: " + mn);
    URL restURL = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) restURL.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("User-Agent", userAgent);
    //conn.setRequestProperty("Content-Type", contentTypeURLENCODED);
    conn.setRequestProperty("Content-Type", contentTypeJSON);
    conn.setDoOutput(true);/*from   w w  w  .ja  va 2s.  co  m*/
    DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
    wr.writeBytes(requestBody);
    wr.flush();
    wr.close();
    int responseCode = conn.getResponseCode();
    System.out.println(fqcn + " :: " + mn + " : " + "Sending 'HTTP POST' request");
    System.out.println(fqcn + " :: " + mn + " : " + "Response Code : " + responseCode);
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String inputLine;
    StringBuilder jsonResponse = new StringBuilder();
    while ((inputLine = in.readLine()) != null) {
        jsonResponse.append(inputLine);
    }
    in.close();
    System.out.println(fqcn + " :: " + mn + " : " + jsonResponse.toString());
    return new String(jsonResponse);
}

From source file:com.androidzeitgeist.dashwatch.common.IOUtil.java

public static InputStream openUri(Context context, Uri uri, String reqContentTypeSubstring)
        throws OpenUriException {

    if (uri == null) {
        throw new IllegalArgumentException("Uri cannot be empty");
    }/*from  ww w .  j  ava  2  s.com*/

    String scheme = uri.getScheme();
    if (scheme == null) {
        throw new OpenUriException(false, new IOException("Uri had no scheme"));
    }

    InputStream in = null;
    if ("content".equals(scheme)) {
        try {
            in = context.getContentResolver().openInputStream(uri);
        } catch (FileNotFoundException e) {
            throw new OpenUriException(false, e);
        } catch (SecurityException e) {
            throw new OpenUriException(false, e);
        }

    } else if ("file".equals(scheme)) {
        List<String> segments = uri.getPathSegments();
        if (segments != null && segments.size() > 1 && "android_asset".equals(segments.get(0))) {
            AssetManager assetManager = context.getAssets();
            StringBuilder assetPath = new StringBuilder();
            for (int i = 1; i < segments.size(); i++) {
                if (i > 1) {
                    assetPath.append("/");
                }
                assetPath.append(segments.get(i));
            }
            try {
                in = assetManager.open(assetPath.toString());
            } catch (IOException e) {
                throw new OpenUriException(false, e);
            }
        } else {
            try {
                in = new FileInputStream(new File(uri.getPath()));
            } catch (FileNotFoundException e) {
                throw new OpenUriException(false, e);
            }
        }

    } else if ("http".equals(scheme) || "https".equals(scheme)) {
        OkHttpClient client = new OkHttpClient();
        HttpURLConnection conn = null;
        int responseCode = 0;
        String responseMessage = null;
        try {
            conn = client.open(new URL(uri.toString()));
            conn.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT);
            conn.setReadTimeout(DEFAULT_READ_TIMEOUT);
            responseCode = conn.getResponseCode();
            responseMessage = conn.getResponseMessage();
            if (!(responseCode >= 200 && responseCode < 300)) {
                throw new IOException("HTTP error response.");
            }
            if (reqContentTypeSubstring != null) {
                String contentType = conn.getContentType();
                if (contentType == null || contentType.indexOf(reqContentTypeSubstring) < 0) {
                    throw new IOException("HTTP content type '" + contentType + "' didn't match '"
                            + reqContentTypeSubstring + "'.");
                }
            }
            in = conn.getInputStream();

        } catch (MalformedURLException e) {
            throw new OpenUriException(false, e);
        } catch (IOException e) {
            if (conn != null && responseCode > 0) {
                throw new OpenUriException(500 <= responseCode && responseCode < 600, responseMessage, e);
            } else {
                throw new OpenUriException(false, e);
            }

        }
    }

    return in;
}