Example usage for java.net HttpURLConnection connect

List of usage examples for java.net HttpURLConnection connect

Introduction

In this page you can find the example usage for java.net HttpURLConnection connect.

Prototype

public abstract void connect() throws IOException;

Source Link

Document

Opens a communications link to the resource referenced by this URL, if such a connection has not already been established.

Usage

From source file:info.dc585.hpt.NetworkUtilities.java

/**
 * Download the avatar image from the server.
 *
 * @param avatarUrl the URL pointing to the avatar image
 * @return a byte array with the raw JPEG avatar image
 *//*w  w  w . j  a v  a2 s .co  m*/
public static Bitmap downloadBitmap(final String avatarUrl) {

    // If there is no avatar, we're done
    if (TextUtils.isEmpty(avatarUrl)) {
        return null;
    }

    try {
        //Log.v(TAG, "Downloading avatar: " + avatarUrl);
        // Request the avatar image from the server, and create a bitmap
        // object from the stream we get back.
        URL url = new URL(avatarUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.connect();
        try {
            final BitmapFactory.Options options = new BitmapFactory.Options();
            final Bitmap avatar = BitmapFactory.decodeStream(connection.getInputStream(), null, options);

            return avatar;

        } finally {
            connection.disconnect();
        }
    } catch (MalformedURLException muex) {
        // A bad URL - nothing we can really do about it here...
        Log.e(TAG, "Malformed avatar URL: " + avatarUrl, muex);
    } catch (IOException ioex) {
        // If we're unable to download the avatar, it's a bummer but not the
        // end of the world. We'll try to get it next time we sync.
        Log.e(TAG, "Failed to download user avatar: " + avatarUrl, ioex);
    }
    return null;
}

From source file:fr.free.movierenamer.utils.URIRequest.java

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

From source file:jmc.util.UtlFbComents.java

public static String getJSONComentarios(String url, Long numComents) throws JMCException {
    String linea = "";
    String buf = "";

    try {//from   w  ww.  j  a  v a2  s . c  om
        Properties props = ConfigPropiedades.getProperties("props_config.properties");
        CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
        URL ur = new URL(
                "http://graph.facebook.com/comments?id=" + url + "&limit=" + numComents + "&filter=stream");
        HttpURLConnection cn = (HttpURLConnection) ur.openConnection();

        cn.setRequestProperty("user-agent", props.getProperty("navegador"));
        cn.setInstanceFollowRedirects(false);
        cn.setUseCaches(false);
        cn.connect();

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

        while ((linea = br.readLine()) != null) {
            buf.concat(linea);
        }
        cn.disconnect();

    } catch (IOException e) {
        throw new JMCException(e);
    }
    return buf;
}

From source file:com.wx.kernel.util.HttpKit.java

/**
 * Send POST request// w w w.j a  v  a  2  s.com
 */
public static String post(String url, Map<String, String> queryParas, String data,
        Map<String, String> headers) {
    HttpURLConnection conn = null;
    try {
        conn = getHttpConnection(buildUrlWithQueryString(url, queryParas), POST, headers);
        conn.connect();

        OutputStream out = conn.getOutputStream();
        out.write(data.getBytes(CHARSET));
        out.flush();
        out.close();

        return readResponseString(conn);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:com.socialize.util.ImageUtils.java

public static Bitmap getBitmapFromURL(String src) {
    Bitmap myBitmap = null;//from w  w  w.ja  v  a 2s  .  c  o m
    HttpURLConnection connection = null;

    try {
        URL url = new URL(src);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        myBitmap = BitmapFactory.decodeStream(input);
    } catch (IOException e) {
        e.printStackTrace();
        myBitmap = null;
    } finally {
        try {
            connection.disconnect();
        } catch (Exception ignored) {
        }
    }

    return myBitmap;
}

From source file:com.linkedin.pinot.controller.helix.ControllerTest.java

public static String sendDeleteRequest(String urlString) throws IOException {
    final long start = System.currentTimeMillis();

    final URL url = new URL(urlString);
    final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);//from  www.  ja  va  2 s .c  o  m
    conn.setRequestMethod("DELETE");
    conn.connect();

    final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

    final StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }

    final long stop = System.currentTimeMillis();

    LOGGER.info(" Time take for Request : " + urlString + " in ms:" + (stop - start));

    return sb.toString();
}

From source file:jmc.util.UtlFbComents.java

public static void getURLComentarios(String url, Long numComents) throws JMCException {

    File f = null;/*  ww  w  .java2 s. c o  m*/

    try {
        Properties props = ConfigPropiedades.getProperties("props_config.properties");
        CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
        URL ur = new URL(
                "http://graph.facebook.com/comments?id=" + url + "&limit=" + numComents + "&filter=stream");
        HttpURLConnection cn = (HttpURLConnection) ur.openConnection();

        cn.setRequestProperty("user-agent", props.getProperty("navegador"));
        cn.setInstanceFollowRedirects(false);
        cn.setUseCaches(false);
        cn.connect();

        BufferedReader br = new BufferedReader(new InputStreamReader(cn.getInputStream()));
        String dirTempHtml = props.getProperty("archive_json") + "/";
        File fld = new File(dirTempHtml);

        boolean creado = fld.exists() ? true : fld.mkdir();

        if (creado) {
            String archFile = "archivo.json";
            String archivo = dirTempHtml + archFile;
            String linea = null;

            f = new File(archivo);
            BufferedWriter bw = new BufferedWriter(new FileWriter(f));
            while ((linea = br.readLine()) != null) {
                bw.append(linea);
            }
            bw.close();

            cn.disconnect();

            List<Fbcoment> lfb = Convertidor.getFbcomentObjects(1l, archivo);
            // Fbcoment.actComents(idContenido, lfb);

        } else {
            cn.disconnect();
        }

    } catch (IOException e) {
        throw new JMCException(e);
    }
}

From source file:Main.java

public static String readTextFromURL(String urlString) throws IOException {

    HttpURLConnection urlConnection = null;

    URL url = new URL(urlString);

    urlConnection = (HttpURLConnection) url.openConnection();

    urlConnection.setRequestMethod("GET");
    urlConnection.setReadTimeout(10000 /* milliseconds */);
    urlConnection.setConnectTimeout(15000 /* milliseconds */);

    urlConnection.setDoOutput(true);//from   w  w  w . jav a2  s  .c om

    urlConnection.connect();

    BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));

    char[] buffer = new char[1024];

    String jsonString = new String();

    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = br.readLine()) != null) {
        sb.append(line + "\n");
    }
    br.close();

    return sb.toString();
}

From source file:com.mytwitter.Network.NetworkHelper.java

/**
 * Verifies that the handset is connected to the Internet.
 *
 * @return//from  w  w  w . ja v a  2 s . co m
 */
public static boolean connectedToInternet(Context context) throws IOException {

    if (!connectedToNetwork(getConnectivityManager(context)))
        return false;

    URL googleUrl = new URL(WEBADDRESS_GOOGLE_COM_URL);
    HttpURLConnection connection = (HttpURLConnection) googleUrl.openConnection();
    connection.setConnectTimeout(NETWORK_CONNECTION_CONNECT_TIMEOUT);
    connection.connect();

    if (connection.getResponseCode() == HttpStatus.SC_OK)
        return true;

    return false;

    /**
     *  Alternative way (NOT TESTED):
     *
     boolean result = false;
            
     URL url;
     HttpURLConnection connection = null;
            
     try {
     url = new URL(WEBADDRESS_ANDROID_COM_URL);
            
     connection = (HttpURLConnection) url.openConnection();
     connection.setConnectTimeout(NETWORK_CONNECTION_CONNECT_TIMEOUT);
     connection.setReadTimeout(NETWORK_CONNECTION_READ_TIMEOUT);
            
     InetAddress address = InetAddress.getByName(WEBADDRESS_ANDROID_COM_IP);
            
     result = address.isReachable(NETWORK_CONNECTION_CONNECT_TIMEOUT);
            
     // Redirect check is valid only after the response headers have been received
     // InputStream in = new BufferedInputStream(connection.getInputStream());
            
     //            if (url.getHost().equals(connection.getURL().getHost()))
     //                result = true;
            
     } catch (Exception e) {
     e.printStackTrace();
     } finally {
     connection.disconnect();
     }
            
     return result;
     */
}

From source file:jmc.util.UtlFbComents.java

public static void getComentarios(Long idContenido, Long numComents) throws JMCException {

    File f = null;// www  .j  av a  2 s. com

    try {
        Properties props = ConfigPropiedades.getProperties("props_config.properties");
        CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
        URL ur = new URL("http://graph.facebook.com/comments?id="
                + Contenido.getContenido("Where cont_id = '" + idContenido + "'").get(0).getEnlaceURL()
                + "&limit=" + numComents + "&filter=stream");
        HttpURLConnection cn = (HttpURLConnection) ur.openConnection();

        cn.setRequestProperty("user-agent", props.getProperty("navegador"));
        cn.setInstanceFollowRedirects(false);
        cn.setUseCaches(false);
        cn.connect();

        BufferedReader br = new BufferedReader(new InputStreamReader(cn.getInputStream()));
        String dirTempHtml = props.getProperty("archive_json") + "/";
        File fld = new File(dirTempHtml);

        boolean creado = fld.exists() ? true : fld.mkdir();

        if (creado) {
            String archFile = idContenido + ".json";
            String archivo = dirTempHtml + archFile;
            String linea = null;

            f = new File(archivo);
            BufferedWriter bw = new BufferedWriter(new FileWriter(f));
            while ((linea = br.readLine()) != null) {
                bw.append(linea);
            }
            bw.close();

            cn.disconnect();

            List<Fbcoment> lfb = Convertidor.getFbcomentObjects(idContenido, archivo);
            Fbcoment.actComents(idContenido, lfb);

        } else {
            cn.disconnect();
        }

    } catch (IOException e) {
        throw new JMCException(e);
    }
}