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.cyphermessenger.client.SyncRequest.java

public static Captcha requestCaptcha() throws IOException, APIErrorException {
    HttpURLConnection conn = doRequest("captcha");
    if (conn.getResponseCode() != 200) {
        throw new IOException("Server error");
    }/*from w  w w.j  a  v  a2s. c o  m*/
    InputStream in = conn.getInputStream();
    JsonNode node = MAPPER.readTree(in);
    conn.disconnect();
    int statusCode = node.get("status").asInt();
    String captchaTokenString = node.get("captchaToken").asText();
    String captchaHashString = node.get("captchaHash").asText();
    String captchaImageString = node.get("captchaBytes").asText();

    byte[] captchaHash = Utils.BASE64_URL.decode(captchaHashString);
    byte[] captchaImage = Utils.BASE64_URL.decode(captchaImageString);
    if (statusCode == StatusCode.OK) {
        return new Captcha(captchaTokenString, captchaHash, captchaImage);
    } else {
        throw new APIErrorException(statusCode);
    }
}

From source file:com.qsoft.components.gallery.utils.GalleryUtils.java

private static InputStream OpenHttpConnection(String strURL) throws IOException {
    InputStream inputStream = null;
    URL url = new URL(strURL);
    URLConnection conn = url.openConnection();

    try {/*from  www  .  jav  a2 s  . c o m*/
        HttpURLConnection httpConn = (HttpURLConnection) conn;
        httpConn.setRequestMethod("GET");
        httpConn.connect();

        if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            inputStream = httpConn.getInputStream();
        }
    } catch (Exception ex) {
        Log.e("error", ex.toString());
    }
    return inputStream;
}

From source file:org.apache.felix.http.itest.BaseIntegrationTest.java

protected static void assertContent(int expectedRC, String expected, URL url) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    int rc = conn.getResponseCode();
    assertEquals("Unexpected response code,", expectedRC, rc);

    if (rc >= 200 && rc < 500) {
        InputStream is = null;/*from   w w  w .jav a  2s  .co  m*/
        try {
            is = conn.getInputStream();
            assertEquals(expected, slurpAsString(is));
        } finally {
            close(is);
            conn.disconnect();
        }
    } else {
        InputStream is = null;
        try {
            is = conn.getErrorStream();
            assertEquals(expected, slurpAsString(is));
        } finally {
            close(is);
            conn.disconnect();
        }
    }
}

From source file:com.cyphermessenger.client.SyncRequest.java

public static void userLogout(CypherSession session) throws IOException, APIErrorException {
    HttpURLConnection conn = doRequest("logout", session, null);

    if (conn.getResponseCode() != 200) {
        throw new IOException("Server error");
    }//from ww w.  j  a  v a 2s .co  m

    InputStream in = conn.getInputStream();
    JsonNode node = MAPPER.readTree(in);
    conn.disconnect();
    int statusCode = node.get("status").asInt();
    if (statusCode != StatusCode.OK) {
        throw new APIErrorException(statusCode);
    }
}

From source file:com.heliosdecompiler.bootstrapper.Bootstrapper.java

private static void forceUpdate() throws IOException, VcdiffDecodeException {
    File backupFile = new File(DATA_DIR, "helios.jar.bak");
    try {//from  w w  w . ja  va  2 s.  c o  m
        Files.copy(IMPL_FILE.toPath(), backupFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException exception) {
        // We're going to wrap it so end users know what went wrong
        throw new IOException(String.format("Could not back up Helios implementation (%s %s, %s %s)",
                IMPL_FILE.canRead(), IMPL_FILE.canWrite(), backupFile.canRead(), backupFile.canWrite()),
                exception);
    }
    URL latestVersion = new URL("https://ci.samczsun.com/job/Helios/lastStableBuild/buildNumber");
    HttpURLConnection connection = (HttpURLConnection) latestVersion.openConnection();
    if (connection.getResponseCode() == 200) {
        boolean aborted = false;

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        copy(connection.getInputStream(), outputStream);
        String version = new String(outputStream.toByteArray(), "UTF-8");
        System.out.println("Latest version: " + version);
        int intVersion = Integer.parseInt(version);

        loop: while (true) {
            int buildNumber = loadHelios().buildNumber;
            int oldBuildNumber = buildNumber;
            System.out.println("Current Helios version is " + buildNumber);

            if (buildNumber < intVersion) {
                while (buildNumber <= intVersion) {
                    buildNumber++;
                    URL status = new URL("https://ci.samczsun.com/job/Helios/" + buildNumber + "/api/json");
                    HttpURLConnection con = (HttpURLConnection) status.openConnection();
                    if (con.getResponseCode() == 200) {
                        JsonObject object = Json.parse(new InputStreamReader(con.getInputStream())).asObject();
                        if (object.get("result").asString().equals("SUCCESS")) {
                            JsonArray artifacts = object.get("artifacts").asArray();
                            for (JsonValue value : artifacts.values()) {
                                JsonObject artifact = value.asObject();
                                String name = artifact.get("fileName").asString();
                                if (name.contains("helios-") && !name.contains(IMPLEMENTATION_VERSION)) {
                                    JOptionPane.showMessageDialog(null,
                                            "Bootstrapper is out of date. Patching cannot continue");
                                    aborted = true;
                                    break loop;
                                }
                            }
                            URL url = new URL("https://ci.samczsun.com/job/Helios/" + buildNumber
                                    + "/artifact/target/delta.patch");
                            con = (HttpURLConnection) url.openConnection();
                            if (con.getResponseCode() == 200) {
                                File dest = new File(DATA_DIR, "delta.patch");
                                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                                copy(con.getInputStream(), byteArrayOutputStream);
                                FileOutputStream fileOutputStream = new FileOutputStream(dest);
                                fileOutputStream.write(byteArrayOutputStream.toByteArray());
                                fileOutputStream.close();
                                File cur = IMPL_FILE;
                                File old = new File(IMPL_FILE.getAbsolutePath() + "." + oldBuildNumber);
                                if (cur.renameTo(old)) {
                                    VcdiffDecoder.decode(old, dest, cur);
                                    old.delete();
                                    dest.delete();
                                    continue loop;
                                } else {
                                    throw new IllegalArgumentException("Could not rename");
                                }
                            }
                        }
                    } else {
                        JOptionPane.showMessageDialog(null,
                                "Server returned response code " + con.getResponseCode() + " "
                                        + con.getResponseMessage() + "\nAborting patch process",
                                null, JOptionPane.INFORMATION_MESSAGE);
                        aborted = true;
                        break loop;
                    }
                }
            } else {
                break;
            }
        }

        if (!aborted) {
            int buildNumber = loadHelios().buildNumber;
            System.out.println("Running Helios version " + buildNumber);
            JOptionPane.showMessageDialog(null, "Updated Helios to version " + buildNumber + "!");
            Runtime.getRuntime().exec(new String[] { "java", "-jar", BOOTSTRAPPER_FILE.getAbsolutePath() });
        } else {
            try {
                Files.copy(backupFile.toPath(), IMPL_FILE.toPath(), StandardCopyOption.REPLACE_EXISTING);
            } catch (IOException exception) {
                // We're going to wrap it so end users know what went wrong
                throw new IOException("Critical Error! Could not restore Helios implementation to original copy"
                        + "Try relaunching the Bootstrapper. If that doesn't work open a GitHub issue with details",
                        exception);
            }
        }
        System.exit(0);
    } else {
        throw new IOException(connection.getResponseCode() + ": " + connection.getResponseMessage());
    }
}

From source file:org.apache.felix.http.itest.BaseIntegrationTest.java

protected static void assertResponseCode(int expected, URL url) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    try {/*  ww  w . ja  v a  2 s. c  om*/
        assertEquals(expected, conn.getResponseCode());
    } finally {
        conn.disconnect();
    }
}

From source file:com.heliosdecompiler.bootstrapper.Bootstrapper.java

private static HeliosData loadHelios() throws IOException {
    System.out.println("Finding Helios implementation");

    HeliosData data = new HeliosData();

    boolean needsToDownload = !IMPL_FILE.exists();
    if (!needsToDownload) {
        try (JarFile jarFile = new JarFile(IMPL_FILE)) {
            ZipEntry entry = jarFile.getEntry("META-INF/MANIFEST.MF");
            if (entry == null) {
                needsToDownload = true;//from w  w  w.  j  ava  2 s.c  o  m
            } else {
                Manifest manifest = new Manifest(jarFile.getInputStream(entry));
                String ver = manifest.getMainAttributes().getValue("Implementation-Version");
                try {
                    data.buildNumber = Integer.parseInt(ver);
                    data.version = manifest.getMainAttributes().getValue("Version");
                    data.mainClass = manifest.getMainAttributes().getValue("Main-Class");
                } catch (NumberFormatException e) {
                    needsToDownload = true;
                }
            }
        } catch (IOException e) {
            needsToDownload = true;
        }
    }
    if (needsToDownload) {
        URL latestJar = new URL(LATEST_JAR);
        System.out.println("Downloading latest Helios implementation");

        FileOutputStream out = new FileOutputStream(IMPL_FILE);
        HttpURLConnection connection = (HttpURLConnection) latestJar.openConnection();
        if (connection.getResponseCode() == 200) {
            int contentLength = connection.getContentLength();
            if (contentLength > 0) {
                InputStream stream = connection.getInputStream();
                byte[] buffer = new byte[1024];
                int amnt;
                AtomicInteger total = new AtomicInteger();
                AtomicBoolean stop = new AtomicBoolean(false);

                Thread progressBar = new Thread() {
                    public void run() {
                        JPanel panel = new JPanel();
                        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

                        JLabel label = new JLabel();
                        label.setText("Downloading latest Helios build");
                        panel.add(label);

                        GridLayout layout = new GridLayout();
                        layout.setColumns(1);
                        layout.setRows(3);
                        panel.setLayout(layout);
                        JProgressBar pbar = new JProgressBar();
                        pbar.setMinimum(0);
                        pbar.setMaximum(100);
                        panel.add(pbar);

                        JTextArea textArea = new JTextArea(1, 3);
                        textArea.setOpaque(false);
                        textArea.setEditable(false);
                        textArea.setText("Downloaded 00.00MB/00.00MB");
                        panel.add(textArea);

                        JFrame frame = new JFrame();
                        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                        frame.setContentPane(panel);
                        frame.pack();
                        frame.setLocationRelativeTo(null);
                        frame.setVisible(true);

                        while (!stop.get()) {
                            SwingUtilities.invokeLater(
                                    () -> pbar.setValue((int) (100.0 * total.get() / contentLength)));

                            textArea.setText("Downloaded " + bytesToMeg(total.get()) + "MB/"
                                    + bytesToMeg(contentLength) + "MB");
                            try {
                                Thread.sleep(100);
                            } catch (InterruptedException ignored) {
                            }
                        }
                        frame.dispose();
                    }
                };
                progressBar.start();

                while ((amnt = stream.read(buffer)) != -1) {
                    out.write(buffer, 0, amnt);
                    total.addAndGet(amnt);
                }
                stop.set(true);
                return loadHelios();
            } else {
                throw new IOException("Content-Length set to " + connection.getContentLength());
            }
        } else if (connection.getResponseCode() == 404) { // Most likely bootstrapper is out of date
            throw new RuntimeException("Bootstrapper out of date!");
        } else {
            throw new IOException(connection.getResponseCode() + ": " + connection.getResponseMessage());
        }
    }

    return data;
}

From source file:com.cyphermessenger.client.SyncRequest.java

public static List<String> findUser(CypherSession session, String username, int limit)
        throws IOException, APIErrorException {
    String[] keys = new String[] { "username", "limit" };
    String[] vals = new String[] { username, limit + "" };

    HttpURLConnection conn = doRequest("find", session, keys, vals);

    if (conn.getResponseCode() != 200) {
        throw new IOException("Server error");
    }/*from   www .  ja va 2  s  . co  m*/

    JsonNode node = MAPPER.readTree(conn.getInputStream());
    conn.disconnect();
    int statusCode = node.get("status").asInt();
    if (statusCode != StatusCode.OK) {
        throw new APIErrorException(statusCode);
    } else {
        return Utils.MAPPER.treeToValue(node.get("users"), ArrayList.class);
    }
}

From source file:com.cyphermessenger.client.SyncRequest.java

private static JsonNode pullUpdate(CypherSession session, CypherUser contact, String action, Boolean since,
        Long time) throws IOException, APIErrorException {
    String timeBoundary = "since";
    if (since != null && since == UNTIL) {
        timeBoundary = "until";
    }/*  ww w. j  a v  a 2  s  . c  o  m*/
    HashMap<String, String> pairs = new HashMap<>(3);
    pairs.put("action", action);
    if (contact != null) {
        pairs.put("contactID", contact.getUserID().toString());
    }
    if (time != null) {
        pairs.put(timeBoundary, time.toString());
    }
    HttpURLConnection conn = doRequest("pull", session, pairs);
    if (conn.getResponseCode() != 200) {
        throw new IOException("Server error");
    }

    InputStream in = conn.getInputStream();
    JsonNode node = MAPPER.readTree(in);
    conn.disconnect();
    int statusCode = node.get("status").asInt();
    if (statusCode == StatusCode.OK) {
        return node;
    } else {
        throw new APIErrorException(statusCode);
    }
}

From source file:com.cyphermessenger.client.SyncRequest.java

public static void sendMessage(CypherSession session, CypherUser contactUser, CypherMessage message)
        throws IOException, APIErrorException {
    CypherUser user = session.getUser();
    byte[] timestampBytes = Utils.longToBytes(message.getTimestamp());
    int messageIDLong = message.getMessageID();
    Encrypt encryptionCtx = new Encrypt(user.getKey().getSharedSecret(contactUser.getKey()));
    encryptionCtx.updateAuthenticatedData(Utils.longToBytes(messageIDLong));
    encryptionCtx.updateAuthenticatedData(timestampBytes);
    byte[] payload;
    try {/*w  ww  . j  av  a2s  .c o  m*/
        payload = encryptionCtx.process(message.getText().getBytes());
    } catch (InvalidCipherTextException e) {
        throw new RuntimeException(e);
    }
    HashMap<String, String> pairs = new HashMap<>(6);
    pairs.put("payload", Utils.BASE64_URL.encode(payload));
    pairs.put("contactID", contactUser.getUserID() + "");
    pairs.put("messageID", messageIDLong + "");
    pairs.put("messageTimestamp", message.getTimestamp() + "");
    pairs.put("userKeyTimestamp", session.getUser().getKeyTime() + "");
    pairs.put("contactKeyTimestamp", contactUser.getKeyTime() + "");

    HttpURLConnection conn = doRequest("message", session, pairs);
    if (conn.getResponseCode() != 200) {
        throw new IOException("Server error");
    }

    InputStream in = conn.getInputStream();
    JsonNode node = MAPPER.readTree(in);
    conn.disconnect();
    int statusCode = node.get("status").asInt();
    if (statusCode != StatusCode.OK) {
        throw new APIErrorException(statusCode);
    }
}