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:fr.free.movierenamer.utils.URIRequest.java

public static int getResponseCode(URL url, RequestProperty... properties) {
    try {//  w  w  w  .j a v  a 2 s .  c  o  m
        HttpURLConnection huc = (HttpURLConnection) openConnection(url.toURI(), properties);
        huc.setRequestMethod("GET");
        huc.connect();
        return huc.getResponseCode();
    } catch (Exception ex) {
        return 0;
    }
}

From source file:com.meetingninja.csse.database.AgendaDatabaseAdapter.java

public static boolean deleteAgenda(String agendaID) throws IOException {
    // Server URL setup
    String _url = getBaseUri().appendPath(agendaID).build().toString();

    // Establish connection
    URL url = new URL(_url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    // add request header
    conn.setRequestMethod(IRequest.DELETE);
    addRequestHeader(conn, false);/*from w  w  w . ja va  2 s .c  om*/

    // Get server response
    int responseCode = conn.getResponseCode();
    String response = getServerResponse(conn);

    boolean result = false;
    JsonNode tree = MAPPER.readTree(response);
    if (!response.isEmpty()) {
        if (!tree.has(Keys.DELETED)) {
            result = true;
        } else {
            Log.e(TAG, String.format("ErrorID: [%s] %s", tree.get(Keys.ERROR_ID).asText(),
                    tree.get(Keys.ERROR_MESSAGE).asText()));
        }
    }

    conn.disconnect();
    return result;

}

From source file:com.heliosdecompiler.helios.bootloader.Bootloader.java

private static byte[] loadSWTLibrary() throws IOException, NoSuchMethodException, IllegalAccessException,
        InvocationTargetException, ClassNotFoundException {
    String name = getOSName();/* www  . ja v a2 s .  com*/
    if (name == null)
        throw new IllegalArgumentException("Cannot determine OS");
    String arch = getArch();
    if (arch == null)
        throw new IllegalArgumentException("Cannot determine architecture");

    String artifactId = "org.eclipse.swt." + name + "." + arch;
    String swtLocation = artifactId + "-" + SWT_VERSION + ".jar";

    System.out.println("Loading SWT version " + swtLocation);

    byte[] data = null;

    File savedJar = new File(Constants.DATA_DIR, swtLocation);
    if (savedJar.isDirectory() && !savedJar.delete())
        throw new IllegalArgumentException("Saved file is a directory and could not be deleted");

    if (savedJar.exists() && savedJar.canRead()) {
        try {
            System.out.println("Loading from saved file");
            InputStream inputStream = new FileInputStream(savedJar);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            copy(inputStream, outputStream);
            data = outputStream.toByteArray();
        } catch (IOException exception) {
            System.out.println("Failed to load from saved file.");
            exception.printStackTrace(System.out);
        }
    }
    if (data == null) {
        InputStream fromJar = Bootloader.class.getResourceAsStream("/swt/" + swtLocation);
        if (fromJar != null) {
            try {
                System.out.println("Loading from within JAR");
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                copy(fromJar, outputStream);
                data = outputStream.toByteArray();
            } catch (IOException exception) {
                System.out.println("Failed to load within JAR");
                exception.printStackTrace(System.out);
            }
        }
    }
    if (data == null) {
        URL url = new URL("https://maven-eclipse.github.io/maven/org/eclipse/swt/" + artifactId + "/"
                + SWT_VERSION + "/" + swtLocation);
        try {
            System.out.println("Loading over the internet");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            if (connection.getResponseCode() == 200) {
                InputStream fromURL = connection.getInputStream();
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                copy(fromURL, outputStream);
                data = outputStream.toByteArray();
            } else {
                throw new IOException(connection.getResponseCode() + ": " + connection.getResponseMessage());
            }
        } catch (IOException exception) {
            System.out.println("Failed to load over the internet");
            exception.printStackTrace(System.out);
        }
    }

    if (data == null) {
        throw new IllegalArgumentException("Failed to load SWT");
    }

    if (!savedJar.exists()) {
        try {
            System.out.println("Writing to saved file");
            if (savedJar.createNewFile()) {
                FileOutputStream fileOutputStream = new FileOutputStream(savedJar);
                fileOutputStream.write(data);
                fileOutputStream.close();
            } else {
                throw new IOException("Could not create new file");
            }
        } catch (IOException exception) {
            System.out.println("Failed to write to saved file");
            exception.printStackTrace(System.out);
        }
    }

    byte[] dd = data;

    URL.setURLStreamHandlerFactory(protocol -> { //JarInJar!
        if (protocol.equals("swt")) {
            return new URLStreamHandler() {
                protected URLConnection openConnection(URL u) {
                    return new URLConnection(u) {
                        public void connect() {
                        }

                        public InputStream getInputStream() {
                            return new ByteArrayInputStream(dd);
                        }
                    };
                }

                protected void parseURL(URL u, String spec, int start, int limit) {
                    // Don't parse or it's too slow
                }
            };
        }
        return null;
    });

    ClassLoader classLoader = Bootloader.class.getClassLoader();
    Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
    method.setAccessible(true);
    method.invoke(classLoader, new URL("swt://load"));

    return data;
}

From source file:com.mycompany.craftdemo.utility.java

public static JSONObject getAPIData(String apiURL) {
    try {//  w  w  w.  ja va2s  . c  o  m
        URL url = new URL(apiURL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");

        if (conn.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
        StringBuilder sb = new StringBuilder();
        String output;
        while ((output = br.readLine()) != null)
            sb.append(output);

        String res = sb.toString();
        JSONParser parser = new JSONParser();
        JSONObject json = null;
        try {
            json = (JSONObject) parser.parse(res);
        } catch (ParseException ex) {
            ex.printStackTrace();
        }
        //resturn api data in json format
        return json;

    } catch (MalformedURLException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }
    return null;
}

From source file:org.pixmob.fm2.util.HttpUtils.java

/**
 * Download a file.//from w ww .  ja  v a 2  s.  c  o  m
 */
public static void downloadToFile(Context context, String uri, Set<String> cookies, File outputFile)
        throws IOException {
    final HttpURLConnection conn = newRequest(context, uri, cookies);
    try {
        conn.connect();

        final int sc = conn.getResponseCode();
        if (sc != HttpURLConnection.HTTP_OK) {
            throw new IOException("Cannot download file: " + uri + "; statusCode=" + sc);
        }

        final InputStream input = getInputStream(conn);
        IOUtils.writeToFile(input, outputFile);
    } finally {
        conn.disconnect();
    }
}

From source file:com.meetingninja.csse.database.NotesDatabaseAdapter.java

public static Note getNote(final String noteID) throws Exception {
    // Server URL setup
    String _url = getBaseUri().appendPath(noteID).build().toString();

    // Establish connection
    URL url = new URL(_url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    // add request header
    conn.setRequestMethod(IRequest.GET);
    addRequestHeader(conn, false);/*from  ww  w. ja v  a 2  s.  c o  m*/

    // Get server response
    int responseCode = conn.getResponseCode();
    String response = getServerResponse(conn);
    JsonNode userNode = MAPPER.readTree(response);

    Note ret = parseNote(userNode);
    return ret;
}

From source file:gr.scify.newsum.Utils.java

public static boolean urlChanged(String url) {
    try {/*w  ww .  j a v  a2  s  . c  o m*/
        HttpURLConnection.setFollowRedirects(false);
        HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
        con.setRequestMethod("HEAD");
        return (con.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED);
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

From source file:Main.java

/**
 * Return an {@link InputStream} from the given url or null if failed to retrieve the content
 * /*ww  w  .  j a v a 2  s  .  com*/
 * @param uri
 * @return
 */
static InputStream openRemoteInputStream(Uri uri) {
    java.net.URL finalUrl;
    try {
        finalUrl = new java.net.URL(uri.toString());
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return null;
    }

    HttpURLConnection connection;
    try {
        connection = (HttpURLConnection) finalUrl.openConnection();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

    connection.setInstanceFollowRedirects(false);
    int code;
    try {
        code = connection.getResponseCode();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

    // permanent redirection
    if (code == HttpURLConnection.HTTP_MOVED_PERM || code == HttpURLConnection.HTTP_MOVED_TEMP
            || code == HttpURLConnection.HTTP_SEE_OTHER) {
        String newLocation = connection.getHeaderField("Location");
        return openRemoteInputStream(Uri.parse(newLocation));
    }

    try {
        return (InputStream) finalUrl.getContent();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.appdynamics.common.RESTClient.java

public static void sendGet(String urlString, String apiKey) {

    try {/* w  w  w  .j av a2 s .co m*/

        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("Authorization",
                "Basic " + new String(Base64.encodeBase64((apiKey).getBytes())));

        if (conn.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
        }

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

        String output;
        logger.info("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            logger.info(output);
        }

        conn.disconnect();

    } catch (MalformedURLException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }

}

From source file:com.ibuildapp.romanblack.CataloguePlugin.imageloader.Utils.java

public static String downloadFile(Context context, String url, String md5) {
    final int BYTE_ARRAY_SIZE = 8024;
    final int CONNECTION_TIMEOUT = 30000;
    final int READ_TIMEOUT = 30000;

    try {/*from  w  ww.  j a  v a  2 s  .  c o m*/
        for (int i = 0; i < 3; i++) {
            URL fileUrl = new URL(URLDecoder.decode(url));
            HttpURLConnection connection = (HttpURLConnection) fileUrl.openConnection();
            connection.setConnectTimeout(CONNECTION_TIMEOUT);
            connection.setReadTimeout(READ_TIMEOUT);
            connection.connect();

            int status = connection.getResponseCode();

            if (status >= HttpStatus.SC_BAD_REQUEST) {
                connection.disconnect();

                continue;
            }

            BufferedInputStream bufferedInputStream = new BufferedInputStream(connection.getInputStream());
            File file = new File(StaticData.getCachePath(context) + md5);

            if (!file.exists()) {
                new File(StaticData.getCachePath(context)).mkdirs();
                file.createNewFile();
            }

            FileOutputStream fileOutputStream = new FileOutputStream(file, false);
            int byteCount;
            byte[] buffer = new byte[BYTE_ARRAY_SIZE];

            while ((byteCount = bufferedInputStream.read(buffer, 0, BYTE_ARRAY_SIZE)) != -1)
                fileOutputStream.write(buffer, 0, byteCount);

            bufferedInputStream.close();
            fileOutputStream.flush();
            fileOutputStream.close();

            return file.getAbsolutePath();
        }
    } catch (Exception e) {
        e.printStackTrace();

        return null;
    }

    return null;
}