Example usage for java.net URL openConnection

List of usage examples for java.net URL openConnection

Introduction

In this page you can find the example usage for java.net URL openConnection.

Prototype

public URLConnection openConnection() throws java.io.IOException 

Source Link

Document

Returns a java.net.URLConnection URLConnection instance that represents a connection to the remote object referred to by the URL .

Usage

From source file:software.uncharted.util.HTTPUtil.java

public static String post(String urlToRead, String postData) {
    URL url;
    HttpURLConnection conn;/*from   w w  w.  j av  a 2  s  . c om*/
    try {
        url = new URL(urlToRead);
        conn = (HttpURLConnection) url.openConnection();

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

        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(postData);
        wr.flush();
        wr.close();

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        int nRead;
        byte[] data = new byte[16384];
        InputStream is = conn.getInputStream();
        while ((nRead = is.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, nRead);
        }
        buffer.flush();
        return buffer.toString();
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("Failed to read URL: " + urlToRead + " <" + e.getMessage() + ">");
    }
    return null;
}

From source file:com.jiubang.core.util.HttpUtils.java

/**
 * Open an URL connection. If HTTPS, accepts any certificate even if not
 * valid, and connects to any host name.
 * /*from  w  w w .j  a va 2  s  .c om*/
 * @param url
 *            The destination URL, HTTP or HTTPS.
 * @return The URLConnection.
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
private static URLConnection getConnection(URL url)
        throws IOException, NoSuchAlgorithmException, KeyManagementException {
    URLConnection conn = url.openConnection();
    if (conn instanceof HttpsURLConnection) {
        // Trust all certificates
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(new KeyManager[0], TRUST_MANAGER, new SecureRandom());
        SSLSocketFactory socketFactory = context.getSocketFactory();
        ((HttpsURLConnection) conn).setSSLSocketFactory(socketFactory);

        // Allow all hostnames
        ((HttpsURLConnection) conn).setHostnameVerifier(HOSTNAME_VERIFIER);

    }
    conn.setConnectTimeout(SOCKET_TIMEOUT);
    conn.setReadTimeout(SOCKET_TIMEOUT);
    return conn;
}

From source file:com.quackware.handsfreemusic.Utility.java

public static String getSourceCode(URL url) {
    Object content = null;//w w w .  j  av  a2s  . c  om
    try {

        HttpURLConnection uc = (HttpURLConnection) url.openConnection();
        uc.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows; U; Windows NT 6.1; ru; rv:1.9.2.4) Gecko/20100513 Firefox/3.6.4");
        uc.connect();
        InputStream stream = uc.getInputStream();
        if (stream != null) {
            content = readStream(uc.getContentLength(), stream);
        } else if ((content = uc.getContent()) != null && content instanceof java.io.InputStream)
            content = readStream(uc.getContentLength(), (java.io.InputStream) content);
        uc.disconnect();

    } catch (Exception ex) {
        return null;
    }
    if (content != null && content instanceof String) {
        String html = (String) content;
        return html;
    } else {
        return null;
    }
}

From source file:com.gabrielluz.megasenaanalyzer.MegaSenaAnalyzer.java

public static byte[] downloadFile(String fileUrl) throws IOException {
    java.net.CookieManager cm;/* ww w. j  a v a 2s .c o m*/
    cm = new java.net.CookieManager();
    java.net.CookieHandler.setDefault(cm);
    URL url = new URL(fileUrl);
    HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
    int responseCode = httpConn.getResponseCode();
    if (responseCode == HttpURLConnection.HTTP_OK) {
        try (InputStream inputStream = httpConn.getInputStream()) {
            return MegaSenaAnalyzer.unZipIt(inputStream);
        }
    } else {
        System.out.println("No file to download. Server replied HTTP code: " + responseCode);
        httpConn.disconnect();
        return null;
    }
}

From source file:controlador.Red.java

/**
 * Obtencion de un JTree mapeado pasandole una URL de un server FTP.
 * @param url URL formateada de la siguiente manera: protocolo://user:pwd@ip:puerto".
 * @return JTree formateado para hacer un set directamente.
 *//* w w  w .j  a v  a2  s.c  om*/
public static JTree setArbolFTP(URL url) {
    try {
        URLConnection conn = url.openConnection();
        InputStream is = conn.getInputStream();

        JTree tree = new Mapeador().mapearServer(is);

        is.close();
        return tree;
    } catch (IOException ex) {
        System.out.println("Problema al hacer set del ArbolFTP: " + ex.getLocalizedMessage());
    }

    return null;
}

From source file:com.choices.imagecompare.urlsfetcher.ImageUrlsFetcher.java

@Nullable
private static String downloadContentAsString(String urlString) throws IOException {
    InputStream is = null;/*from  ww w  .  ja  v a 2  s .  c  om*/
    try {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Authorization", IMGUR_CLIENT_ID);
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        // Starts the query
        conn.connect();
        int response = conn.getResponseCode();
        if (response != SC_OK) {
            FLog.e(TAG, "Album request returned %s", response);
            return null;
        }
        is = conn.getInputStream();
        return readAsString(is);
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:com.android.dialer.omni.PlaceUtil.java

/**
 * Executes a GET request and return a JSON object
 * @param url The API URL/*from ww w  .  j  a va2s .c  om*/
 * @return the JSON object
 * @throws IOException
 * @throws JSONException
 */
public static JSONObject getJsonRequest(String url) throws IOException, JSONException {
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    con.setRequestMethod("GET");

    if (DEBUG)
        Log.d(TAG, "Getting JSON from: " + url);

    con.setDoOutput(true);
    int responseCode = con.getResponseCode();

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    JSONObject json = new JSONObject(response.toString());
    return json;
}

From source file:com.tubes2.User.userPaket.java

public static ArrayList<String> readUser(String Username) throws IOException {
    String URLi = "https://popping-fire-1228.firebaseio.com/users/";
    ArrayList<String> dataUser = new ArrayList<String>();
    try {//from w  ww.ja va 2  s.co  m
        URL url = new URL(URLi + Username + ".json");
        URLConnection connection = url.openConnection();
        JSONObject jsonUser = new JSONObject(IOUtils.toString(connection.getInputStream()));
        dataUser.add(0, jsonUser.getString("nama"));
        dataUser.add(1, jsonUser.getString("username"));
        dataUser.add(2, jsonUser.getString("password"));
        dataUser.add(3, jsonUser.getString("email"));
        dataUser.add(4, jsonUser.getString("status"));
    } catch (JSONException ex) {

    } catch (IOException ex) {

    }
    return dataUser;
}

From source file:ly.stealth.punxsutawney.Marathon.java

private static JSONObject sendRequest(String uri, String method, JSONObject json) throws IOException {
    URL url = new URL(Marathon.url + uri);
    HttpURLConnection c = (HttpURLConnection) url.openConnection();
    try {/*from   w w  w.  jav a2  s.  c o  m*/
        c.setRequestMethod(method);

        if (method.equalsIgnoreCase("POST")) {
            byte[] body = json.toString().getBytes("utf-8");
            c.setDoOutput(true);
            c.setRequestProperty("Content-Type", "application/json");
            c.setRequestProperty("Content-Length", "" + body.length);
            c.getOutputStream().write(body);
        }

        return (JSONObject) JSONValue.parse(new InputStreamReader(c.getInputStream(), "utf-8"));
    } catch (IOException e) {
        if (c.getResponseCode() == 404 && method.equals("GET"))
            return null;

        ByteArrayOutputStream response = new ByteArrayOutputStream();
        InputStream err = c.getErrorStream();
        if (err == null)
            throw e;

        Util.copyAndClose(err, response);
        IOException ne = new IOException(e.getMessage() + ": " + response.toString("utf-8"));
        ne.setStackTrace(e.getStackTrace());
        throw ne;
    } finally {
        c.disconnect();
    }
}

From source file:Main.java

public static synchronized boolean isConnect(String url) {
    URL urlStr;
    HttpURLConnection connection;
    if (url == null || url.length() <= 0) {
        return false;
    }//w  w  w  .  ja  v  a  2  s .  com
    try {
        urlStr = new URL(url);
        connection = (HttpURLConnection) urlStr.openConnection();
        int state = connection.getResponseCode();
        if (state == 200) {
            return true;
        }
    } catch (Exception ex) {
        return false;
    }
    return false;
}