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:com.reactivetechnologies.jaxrs.RestServerTest.java

static String sendPost(String url, String content) throws IOException {

    StringBuilder response = new StringBuilder();
    HttpURLConnection con = null;
    BufferedReader in = null;/*from  w w w .ja  v  a 2 s . com*/
    try {
        URL obj = new URL(url);
        con = (HttpURLConnection) obj.openConnection();

        // optional default is GET
        con.setRequestMethod("POST");

        //add request header
        con.setRequestProperty("User-Agent", "Mozilla/5.0");
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeUTF(content);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
        } else {
            throw new IOException("Response Code: " + responseCode);
        }

        return response.toString();
    } catch (IOException e) {
        throw e;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {

            }
        }
        if (con != null) {
            con.disconnect();
        }
    }

}

From source file:ja.ohac.wallet.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> requestExchangeRates(final URL url, final String userAgent,
        final String source, final String... fields) {
    final long start = System.currentTimeMillis();

    HttpURLConnection connection = null;
    Reader reader = null;/*from w  w w .  j  a  v a2 s .co m*/

    try {
        connection = (HttpURLConnection) url.openConnection();

        connection.setInstanceFollowRedirects(false);
        connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.addRequestProperty("User-Agent", userAgent);
        connection.addRequestProperty("Accept-Encoding", "gzip");
        connection.connect();

        final int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            final String contentEncoding = connection.getContentEncoding();

            InputStream is = new BufferedInputStream(connection.getInputStream(), 1024);
            if ("gzip".equalsIgnoreCase(contentEncoding))
                is = new GZIPInputStream(is);

            reader = new InputStreamReader(is, Charsets.UTF_8);
            final StringBuilder content = new StringBuilder();
            final long length = Io.copy(reader, content);

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

            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);

                    for (final String field : fields) {
                        final String rateStr = o.optString(field, null);

                        if (rateStr != null) {
                            try {
                                final BigInteger rate = GenericUtils.parseCoin(rateStr, 0);

                                if (rate.signum() > 0) {
                                    rates.put(currencyCode, new ExchangeRate(currencyCode, rate, source));
                                    break;
                                }
                            } catch (final ArithmeticException x) {
                                log.warn("problem fetching {} exchange rate from {} ({}): {}", currencyCode,
                                        url, contentEncoding, x.getMessage());
                            }
                        }
                    }
                }
            }

            log.info("fetched exchange rates from {} ({}), {} chars, took {} ms", url, contentEncoding, length,
                    System.currentTimeMillis() - start);

            return rates;
        } else {
            log.warn("http status {} when fetching exchange rates from {}", responseCode, url);
        }
    } catch (final Exception x) {
        log.warn("problem fetching exchange rates from " + url, x);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException x) {
                // swallow
            }
        }

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

    return null;
}

From source file:com.reactivetechnologies.jaxrs.RestServerTest.java

static String sendDelete(String url, String content) throws IOException {

    StringBuilder response = new StringBuilder();
    HttpURLConnection con = null;
    BufferedReader in = null;//from  w  w w .  jav a2 s . co  m
    try {
        URL obj = new URL(url);
        con = (HttpURLConnection) obj.openConnection();

        // optional default is GET
        con.setRequestMethod("DELETE");

        //add request header
        con.setRequestProperty("User-Agent", "Mozilla/5.0");
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeUTF(content);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
        } else {
            throw new IOException("Response Code: " + responseCode);
        }

        return response.toString();
    } catch (IOException e) {
        throw e;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {

            }
        }
        if (con != null) {
            con.disconnect();
        }
    }

}

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

public static String doPostUser(String url, Map<String, String> sessionTokens, String requestBody,
        boolean isEncodingNeeded) throws IOException {
    String mn = "doIO(POST : " + url + ", " + requestBody + "sessionTokens : " + sessionTokens + " )";
    System.out.println(fqcn + " :: " + mn);
    URL restURL = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) restURL.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("User-Agent", userAgent);
    if (isEncodingNeeded)
        //conn.setRequestProperty("Content-Type", contentTypeURLENCODED);
        conn.setRequestProperty("Content-Type", contentTypeJSON);
    else/*from   w w  w . j a  v  a  2s. com*/
        conn.setRequestProperty("Content-Type", "text/plain;charset=UTF-8");

    conn.setRequestProperty("Authorization", sessionTokens.toString());
    conn.setDoOutput(true);
    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:net.ftb.util.DownloadUtils.java

/**
 * @param file - the name of the file, as saved to the repo (including extension)
 * @return - the direct link/* ww  w  .  j  av a 2s  .c  o  m*/
 */
public static String getCreeperhostLink(String file) {
    String resolved = (downloadServers.containsKey(Settings.getSettings().getDownloadServer()))
            ? "http://" + downloadServers.get(Settings.getSettings().getDownloadServer())
            : Locations.masterRepo;
    resolved += "/FTB2/" + file;
    HttpURLConnection connection = null;
    try {
        connection = (HttpURLConnection) new URL(resolved).openConnection();
        connection.setRequestProperty("Cache-Control", "no-transform");
        connection.setRequestMethod("HEAD");
        for (String server : downloadServers.values()) {
            if (connection.getResponseCode() != 200) {
                if (!server.contains("creeper")) {
                    file = file.replaceAll("%5E", "/");
                }

                resolved = "http://" + server + "/FTB2/" + file;
                connection = (HttpURLConnection) new URL(resolved).openConnection();
                connection.setRequestProperty("Cache-Control", "no-transform");
                connection.setRequestMethod("HEAD");
            } else {
                break;
            }
        }
    } catch (IOException e) {
    }
    connection.disconnect();
    return resolved;
}

From source file:Main.java

protected static String getResponseAsString(HttpURLConnection conn, boolean responseError) throws IOException {
    String charset = getResponseCharset(conn.getContentType());
    String header = conn.getHeaderField("Content-Encoding");
    boolean isGzip = false;
    if (header != null && header.toLowerCase().contains("gzip")) {
        isGzip = true;/*from  w  w  w  .  j  a va 2  s  . co m*/
    }
    InputStream es = conn.getErrorStream();
    if (es == null) {
        InputStream input = conn.getInputStream();
        if (isGzip) {
            input = new GZIPInputStream(input);
        }
        return getStreamAsString(input, charset);
    } else {
        if (isGzip) {
            es = new GZIPInputStream(es);
        }
        String msg = getStreamAsString(es, charset);
        if (TextUtils.isEmpty(msg)) {
            throw new IOException(conn.getResponseCode() + ":" + conn.getResponseMessage());
        } else if (responseError) {
            return msg;
        } else {
            throw new IOException(msg);
        }
    }
}

From source file:io.apiman.manager.test.es.ESMetricsAccessorTest.java

private static void loadTestData() throws Exception {
    String url = "http://localhost:6500/_bulk";
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestMethod("POST");
    conn.setDoInput(true);/*w ww .  jav  a2s. c  o m*/
    conn.setDoOutput(true);
    OutputStream os = conn.getOutputStream();
    InputStream is = ESMetricsAccessorTest.class.getResourceAsStream("bulk-metrics-data.txt");
    IOUtils.copy(is, os);
    IOUtils.closeQuietly(is);
    IOUtils.closeQuietly(os);
    if (conn.getResponseCode() > 299) {
        IOUtils.copy(conn.getInputStream(), System.err);
        throw new IOException("Bulk load of data failed with: " + conn.getResponseMessage());
    }

    client.execute(new Refresh.Builder().addIndex("apiman_metrics").refresh(true).build());
}

From source file:com.example.pabrto.AppEngineClient.java

public static int delete(URL uri, Map<String, List<String>> headers) {
    //DELETE delete = new DELETE(uri, headers);
    int s = 0;/*w  w w  .  j  a va  2s  .  co m*/
    HttpURLConnection httpURLConnection = null;
    try {
        httpURLConnection = (HttpURLConnection) uri.openConnection();
        if (headers != null) {
            for (String header : headers.keySet()) {
                for (String value : headers.get(header)) {
                    httpURLConnection.addRequestProperty(header, value);
                }
            }
        }
        httpURLConnection.setRequestMethod("DELETE");
        //httpURLConnection.connect();
        s = httpURLConnection.getResponseCode();
        Log.d("TAG", "Response of delete: " + String.valueOf(s));

    } catch (IOException exception) {
        exception.printStackTrace();
    } finally {
        if (httpURLConnection != null) {
            httpURLConnection.disconnect();
        }
    }
    return s;
}

From source file:com.newrelic.agent.Deployments.java

static int recordDeployment(CommandLine cmd, AgentConfig config)/*  37:    */ throws Exception
/*  38:    */ {/* w w  w.j a  v  a2  s .  c  o m*/
    /*  39: 35 */ String appName = config.getApplicationName();
    /*  40: 36 */ if (cmd.hasOption("appname")) {
        /*  41: 37 */ appName = cmd.getOptionValue("appname");
        /*  42:    */ }
    /*  43: 39 */ if (appName == null) {
        /*  44: 40 */ throw new IllegalArgumentException(
                "A deployment must be associated with an application.  Set app_name in newrelic.yml or specify the application name with the -appname switch.");
        /*  45:    */ }
    /*  46: 43 */ System.out.println("Recording a deployment for application " + appName);
    /*  47:    */
    /*  48: 45 */ String uri = "/deployments.xml";
    /*  49: 46 */ String payload = getDeploymentPayload(appName, cmd);
    /*  50: 47 */ String protocol = "http" + (config.isSSL() ? "s" : "");
    /*  51: 48 */ URL url = new URL(protocol, config.getApiHost(), config.getApiPort(), uri);
    /*  52:    */
    /*  53: 50 */ System.out.println(MessageFormat.format("Opening connection to {0}:{1}",
            new Object[] { config.getApiHost(), Integer.toString(config.getApiPort()) }));
    /*  54:    */
    /*  55:    */
    /*  56: 53 */ HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    /*  57: 54 */ conn.setRequestProperty("x-license-key", config.getLicenseKey());
    /*  58:    */
    /*  59: 56 */ conn.setRequestMethod("POST");
    /*  60: 57 */ conn.setConnectTimeout(10000);
    /*  61: 58 */ conn.setReadTimeout(10000);
    /*  62: 59 */ conn.setDoOutput(true);
    /*  63: 60 */ conn.setDoInput(true);
    /*  64:    */
    /*  65: 62 */ conn.setRequestProperty("Content-Length", Integer.toString(payload.length()));
    /*  66: 63 */ conn.setFixedLengthStreamingMode(payload.length());
    /*  67: 64 */ conn.getOutputStream().write(payload.getBytes());
    /*  68:    */
    /*  69: 66 */ int responseCode = conn.getResponseCode();
    /*  70: 67 */ if (responseCode < 300)
    /*  71:    */ {
        /*  72: 68 */ System.out.println("Deployment successfully recorded");
        /*  73:    */ }
    /*  74: 69 */ else if (responseCode == 401)
    /*  75:    */ {
        /*  76: 70 */ System.out.println(
                "Unable to notify New Relic of the deployment because of an authorization error.  Check your license key.");
        /*  77: 71 */ System.out.println("Response message: " + conn.getResponseMessage());
        /*  78:    */ }
    /*  79:    */ else
    /*  80:    */ {
        /*  81: 73 */ System.out.println("Unable to notify New Relic of the deployment");
        /*  82: 74 */ System.out.println("Response message: " + conn.getResponseMessage());
        /*  83:    */ }
    /*  84: 76 */ boolean isError = responseCode >= 300;
    /*  85: 77 */ if ((isError) || (config.isDebugEnabled()))
    /*  86:    */ {
        /*  87: 78 */ System.out.println("Response code: " + responseCode);
        /*  88: 79 */ InputStream inStream = isError ? conn.getErrorStream() : conn.getInputStream();
        /*  89: 81 */ if (inStream != null)
        /*  90:    */ {
            /*  91: 82 */ ByteArrayOutputStream output = new ByteArrayOutputStream();
            /*  92: 83 */ Streams.copy(inStream, output);
            /*  93:    */
            /*  94: 85 */ PrintStream out = isError ? System.err : System.out;
            /*  95:    */
            /*  96: 87 */ out.println(output);
            /*  97:    */ }
        /*  98:    */ }
    /*  99: 90 */ return responseCode;
    /* 100:    */ }

From source file:edu.stanford.muse.launcher.Splash.java

private static boolean isURLAlive(String url) throws IOException {
    try {/*ww w  . ja va2  s.c  o m*/
        // attempt to fetch the page
        // throws a connect exception if the server is not even running
        // so catch it and return false

        // since "index" may auto load default archive, attach it to session, and redirect to "info" page,
        // we need to maintain the session across the pages.
        // see "Maintaining the session" at http://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests
        CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));

        out.println("Testing liveness at " + url);
        HttpURLConnection u = (HttpURLConnection) new URL(url).openConnection();
        if (u.getResponseCode() == 200) {
            u.disconnect();
            return true;
        }
        u.disconnect();
    } catch (ConnectException ce) {
    }
    return false;
}