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:lu.list.itis.dkd.aig.util.FusekiHttpHelper.java

/**
 * Create a new dataset//from  w w  w . j  ava 2  s  .c o m
 * 
 * @param dataSetName
 * @throws IOException
 * @throws HttpException
 */
public static void createDataSet(@NonNull String dataSetName) throws IOException, HttpException {
    logger.info("create dataset: " + dataSetName);

    URL url = new URL(HOST + "/$/datasets");
    final HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
    httpConnection.setUseCaches(false);
    httpConnection.setRequestMethod("POST");
    httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    // set content
    httpConnection.setDoOutput(true);
    final OutputStreamWriter out = new OutputStreamWriter(httpConnection.getOutputStream());
    out.write("dbName=" + URLEncoder.encode(dataSetName, "UTF-8") + "&dbType=mem");
    out.close();

    // handle HTTP/HTTPS strange behaviour
    httpConnection.connect();
    httpConnection.disconnect();

    // handle response
    switch (httpConnection.getResponseCode()) {
    case HttpURLConnection.HTTP_OK:
        break;
    default:
        throw new HttpException(
                httpConnection.getResponseCode() + " message: " + httpConnection.getResponseMessage());
    }
}

From source file:de.schildbach.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;/*  w ww .  ja  v  a2s  .  c om*/

    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 Fiat rate = Fiat.parseFiat(currencyCode, rateStr);

                                if (rate.signum() > 0) {
                                    rates.put(currencyCode, new ExchangeRate(
                                            new org.bitcoinj.utils.ExchangeRate(rate), source));
                                    break;
                                }
                            } catch (final NumberFormatException 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.example.makerecg.NetworkUtilities.java

/**
 * Perform 2-way sync with the server-side ADSampleFrames. We send a request that
 * includes all the locally-dirty contacts so that the server can process
 * those changes, and we receive (and return) a list of contacts that were
 * updated on the server-side that need to be updated locally.
 *
 * @param account The account being synced
 * @param authtoken The authtoken stored in the AccountManager for this
 *            account//  ww  w  .  ja  va  2  s. co  m
 * @param serverSyncState A token returned from the server on the last sync
 * @param dirtyFrames A list of the frames to send to the server
 * @return A list of frames that we need to update locally
 */
public static List<ADSampleFrame> syncSampleFrames(Account account, String authtoken, long serverSyncState,
        List<ADSampleFrame> dirtyFrames)
        throws JSONException, ParseException, IOException, AuthenticationException {

    List<JSONObject> jsonFrames = new ArrayList<JSONObject>();
    for (ADSampleFrame frame : dirtyFrames) {
        jsonFrames.add(frame.toJSONObject());
    }

    JSONArray buffer = new JSONArray(jsonFrames);
    JSONObject top = new JSONObject();

    top.put("data", buffer);

    // Create an array that will hold the server-side ADSampleFrame
    // that have been changed (returned by the server).
    final ArrayList<ADSampleFrame> serverDirtyList = new ArrayList<ADSampleFrame>();

    // Send the updated frames data to the server
    //Log.i(TAG, "Syncing to: " + SYNC_URI);
    URL urlToRequest = new URL(SYNC_URI);
    HttpURLConnection conn = (HttpURLConnection) urlToRequest.openConnection();
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json");
    conn.setRequestProperty("Authorization", "Bearer " + authtoken);

    OutputStream os = conn.getOutputStream();
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
    writer.write(top.toString(1));
    writer.flush();
    writer.close();
    os.close();

    //Log.i(TAG, "body="+top.toString(1));

    int responseCode = conn.getResponseCode();

    if (responseCode == HttpsURLConnection.HTTP_OK) {
        // Our request to the server was successful - so we assume
        // that they accepted all the changes we sent up, and
        // that the response includes the contacts that we need
        // to update on our side...

        // TODO: Only uploading data for now ...

        String response = "";
        String line;
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        while ((line = br.readLine()) != null) {
            response += line;
        }
        br.close();

        //Log.i(TAG, "response="+response);
        /*
        final JSONArray serverContacts = new JSONArray(response);
        Log.d(TAG, response);
        for (int i = 0; i < serverContacts.length(); i++) {
        ADSampleFrame rawContact = ADSampleFrame.valueOf(serverContacts.getJSONObject(i));
        if (rawContact != null) {
            serverDirtyList.add(rawContact);
        }
        }
        */
    } else {
        if (responseCode == HttpsURLConnection.HTTP_UNAUTHORIZED) {
            Log.e(TAG, "Authentication exception in while uploading data");
            throw new AuthenticationException();
        } else {
            Log.e(TAG, "Server error in sending sample frames: " + responseCode);
            throw new IOException();
        }
    }

    return null;
}

From source file:core.RESTCalls.RESTPost.java

public static String httpPost(String urlStr, String[] paramName, String[] paramVal) throws Exception {

    URL url = new URL(urlStr);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");

    conn.setDoOutput(true);/*from w w w.  j a v  a 2s. com*/
    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setAllowUserInteraction(false);
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    OutputStream out = conn.getOutputStream();

    Writer writer = new OutputStreamWriter(out, "UTF-8");

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

        writer.write(paramName[i]);
        writer.write("=");
        writer.write(URLEncoder.encode(paramVal[i], "UTF-8"));
        writer.write("&");
    }

    writer.close();
    out.close();

    if (conn.getResponseCode() != 200)
        throw new IOException(conn.getResponseMessage());

    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));

    StringBuilder sb = new StringBuilder();

    String line;

    while ((line = rd.readLine()) != null)
        sb.append(line + "\n");

    rd.close();

    conn.disconnect();

    return sb.toString();
}

From source file:com.microsoft.azuretools.utils.WebAppUtils.java

public static boolean isUrlAccessible(String url) throws IOException {
    HttpURLConnection.setFollowRedirects(false);
    HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
    con.setRequestMethod("HEAD");
    con.setReadTimeout(Constants.connection_read_timeout_ms);
    try {// w w w . j  a va2s  . c om
        if (con.getResponseCode() != HttpURLConnection.HTTP_OK) {
            return false;
        }
    } catch (IOException ex) {
        return false;
    }
    return true;
}

From source file:bluevia.SendSMS.java

public static void sendBlueViaSMS(String user_email, String phone_number, String sms_message) {
    try {// w  ww  .  j  ava2 s.c o m

        Properties blueviaAccount = Util.getNetworkAccount(user_email, "BlueViaAccount");
        if (blueviaAccount != null) {
            String consumer_key = blueviaAccount.getProperty("BlueViaAccount.consumer_key");
            String consumer_secret = blueviaAccount.getProperty("BlueViaAccount.consumer_secret");
            String access_key = blueviaAccount.getProperty("BlueViaAccount.access_key");
            String access_secret = blueviaAccount.getProperty("BlueViaAccount.access_secret");

            com.google.appengine.api.urlfetch.FetchOptions.Builder.doNotValidateCertificate();

            OAuthConsumer consumer = (OAuthConsumer) new DefaultOAuthConsumer(consumer_key, consumer_secret);
            consumer.setMessageSigner(new HmacSha1MessageSigner());
            consumer.setTokenWithSecret(access_key, access_secret);

            URL apiURI = new URL("https://api.bluevia.com/services/REST/SMS/outbound/requests?version=v1");
            HttpURLConnection request = (HttpURLConnection) apiURI.openConnection();

            request.setRequestProperty("Content-Type", "application/json");
            request.setRequestMethod("POST");
            request.setDoOutput(true);

            consumer.sign(request);
            request.connect();

            String smsTemplate = "{\"smsText\": {\n  \"address\": {\"phoneNumber\": \"%s\"},\n  \"message\": \"%s\",\n  \"originAddress\": {\"alias\": \"%s\"},\n}}";
            String smsMsg = String.format(smsTemplate, phone_number, sms_message, access_key);

            OutputStream os = request.getOutputStream();
            os.write(smsMsg.getBytes());
            os.flush();

            int rc = request.getResponseCode();

            if (rc == HttpURLConnection.HTTP_CREATED)
                log.info(String.format("SMS sent to %s. Text: %s", phone_number, sms_message));
            else
                log.severe(String.format("Error %d sending SMS:%s\n", rc, request.getResponseMessage()));
        } else
            log.warning("BlueVia Account seems to be not configured!");

    } catch (Exception e) {
        log.severe(String.format("Exception sending SMS: %s", e.getMessage()));
    }
}

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

private static boolean killRunningServer(String url) throws IOException {
    try {//from   w w w. j a va 2s. 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
        String http = url
                + "/exit.jsp?message=Shutdown%20request%20from%20a%20different%20instance%20of%20ePADD"; // version num spaces and brackets screw up the URL connection
        err.println("Sending a kill request to " + http);
        HttpURLConnection u = (HttpURLConnection) new URL(http).openConnection();
        u.connect();
        if (u.getResponseCode() == 200) {
            u.disconnect();
            return true;
        }
        u.disconnect();
    } catch (ConnectException ce) {
    }
    return false;
}

From source file:com.truebanana.http.HTTPResponse.java

protected static HTTPResponse from(HTTPRequest request, HttpURLConnection connection, InputStream content) {
    HTTPResponse response = new HTTPResponse();

    response.originalRequest = request;//w  ww  .j  av  a  2 s  . c om
    if (content != null) {
        try {
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            byte[] data = new byte[16384];
            int nRead;

            while ((nRead = content.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, nRead);
            }
            buffer.flush();
            response.content = buffer.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    try {
        response.statusCode = connection.getResponseCode();
    } catch (IOException e) {
    }

    String message = null;
    try {
        message = connection.getResponseMessage();
    } catch (IOException e) {
        message = e.getLocalizedMessage();
    }
    response.responseMessage = response.statusCode + (message != null ? " " + message : "");

    response.headers = connection.getHeaderFields();

    response.requestURL = connection.getURL().toString();

    return response;
}

From source file:net.ftb.util.DownloadUtils.java

/**
 * @param repoURL - URL on the repo/*ww w.  j  av  a2 s.  c o m*/
 * @param fullDebug - should this dump the full cloudflare debug info in the console
 * @return boolean representing if the file exists
 */
public static boolean CloudFlareInspector(String repoURL, boolean fullDebug) {
    try {
        boolean ret;
        HttpURLConnection connection = (HttpURLConnection) new URL(repoURL + "cdn-cgi/trace").openConnection();
        if (!fullDebug)
            connection.setRequestMethod("HEAD");
        Logger.logInfo("CF-RAY: " + connection.getHeaderField("CF-RAY"));
        if (fullDebug)
            Logger.logInfo("CF Debug Info: " + connection.getContent().toString());
        ret = connection.getResponseCode() == 200;
        IOUtils.close(connection);
        return ret;
    } catch (Exception e) {
        return false;
    }
}

From source file:msearch.filmeSuchen.sender.MediathekSrf.java

public static boolean ping(String url) throws SRFException {

    url = url.replaceFirst("https", "http"); // Otherwise an exception may be thrown on invalid SSL certificates.

    try {//  ww w.j a  v a2s .  com
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setConnectTimeout(1000); //1000ms timeout for connect, read timeout to infinity
        connection.setReadTimeout(0);
        int responseCode = connection.getResponseCode();
        connection.disconnect();
        if (responseCode > 399 && responseCode != HttpURLConnection.HTTP_NOT_FOUND) {

            if (responseCode == HttpURLConnection.HTTP_FORBIDDEN) {
                throw new SRFException("TEST");
            }
            //MSLog.debugMeldung("SRF: " + responseCode + " + responseCode " + "Url " + url);
            return false;
        }
        return (200 <= responseCode && responseCode <= 399);

    } catch (IOException exception) {
        return false;
    }
}