List of usage examples for java.net HttpURLConnection connect
public abstract void connect() throws IOException;
From source file:com.grosscommerce.ICEcat.utilities.Downloader.java
public static void download(String urlFrom, String login, String pwd, OutputStream destStream) throws Exception { try {// www . j a v a2s.c om HttpURLConnection uc = prepareConnection(urlFrom, login, pwd); uc.connect(); if (uc.getResponseCode() != HttpURLConnection.HTTP_OK) { Logger.getLogger(Downloader.class.getName()).log(Level.INFO, "Error, code: {0}, message {1}", new Object[] { uc.getResponseCode(), uc.getResponseMessage() }); return; } BufferedInputStream is = null; if ((uc.getContentEncoding() != null && uc.getContentEncoding().toLowerCase().equals("gzip")) || uc.getContentType() != null && uc.getContentType().toLowerCase().contains("gzip")) { is = new BufferedInputStream(new GZIPInputStream(uc.getInputStream())); Logger.getLogger(Downloader.class.getName()).log(Level.INFO, "Will download gzip data from: {0}", urlFrom); } else { is = new BufferedInputStream(uc.getInputStream()); Logger.getLogger(Downloader.class.getName()).log(Level.INFO, "Will download not compressed data from:{0}", urlFrom); } StreamsHelper.copy(is, destStream); destStream.flush(); } catch (Exception ex) { Logger.getLogger(Downloader.class.getName()).log(Level.SEVERE, "URL: " + urlFrom, ex); throw ex; } }
From source file:Main.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 ww . j a va 2s. com*/ public static byte[] downloadAvatar(final String avatarUrl) { // If there is no avatar, we're done if (TextUtils.isEmpty(avatarUrl)) { return null; } try { Log.i(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); // Take the image we received from the server, whatever format it // happens to be in, and convert it to a JPEG image. Note: we're // not resizing the avatar - we assume that the image we get from // the server is a reasonable size... Log.i(TAG, "Converting avatar to JPEG"); ByteArrayOutputStream convertStream = new ByteArrayOutputStream( avatar.getWidth() * avatar.getHeight() * 4); avatar.compress(Bitmap.CompressFormat.JPEG, 95, convertStream); convertStream.flush(); convertStream.close(); // On pre-Honeycomb systems, it's important to call recycle on bitmaps avatar.recycle(); return convertStream.toByteArray(); } finally { connection.disconnect(); } } catch (MalformedURLException muex) { // A bad URL - nothing we can really do about it here... Log.e(TAG, "Malformed avatar URL: " + avatarUrl); } 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); } return null; }
From source file:Main.java
public static Bitmap getHttpBitmap(String url) { URL myFileUrl = null;/*from www . j a va2s. c om*/ Bitmap bitmap = null; try { myFileUrl = new URL(url); } catch (MalformedURLException e) { e.printStackTrace(); } try { HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection(); conn.setConnectTimeout(0); conn.setDoInput(true); conn.connect(); InputStream is = conn.getInputStream(); bitmap = BitmapFactory.decodeStream(is); is.close(); } catch (IOException e) { e.printStackTrace(); } return bitmap; }
From source file:Main.java
public static boolean isURLConnectable(Context context, String url) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo != null && netInfo.isConnected()) { try {/* w w w. j a v a 2 s . c o m*/ HttpURLConnection urlc = (HttpURLConnection) new URL(url).openConnection(); urlc.setConnectTimeout(10 * 1000); // 10 s. urlc.connect(); if (urlc.getResponseCode() == 200) { // 200 = "OK" code (http // connection is fine). Log.wtf("Connection", "Success !"); return true; } else { return false; } } catch (MalformedURLException e1) { return false; } catch (IOException e) { return false; } } return false; }
From source file:Main.java
/** * Return '' or error message if error occurs during URL connection. * //from w w w . j a v a2s.com * @param url The URL to ckeck * @return */ public static String getUrlStatus(String url) { URL u; URLConnection conn; int connectionTimeout = 500; try { u = new URL(url); conn = u.openConnection(); conn.setConnectTimeout(connectionTimeout); // TODO : set proxy if (conn instanceof HttpURLConnection) { HttpURLConnection httpConnection = (HttpURLConnection) conn; httpConnection.setInstanceFollowRedirects(true); httpConnection.connect(); httpConnection.disconnect(); // FIXME : some URL return HTTP200 with an empty reply from server // which trigger SocketException unexpected end of file from server int code = httpConnection.getResponseCode(); if (code == HttpURLConnection.HTTP_OK) { return ""; } else { return "Status: " + code; } } // TODO : Other type of URLConnection } catch (Exception e) { e.printStackTrace(); return e.toString(); } return ""; }
From source file:Main.java
/** * This method checks if the Network available on the device or not. * //www .j a va 2s . c o m * @param context * @return true if network available, false otherwise */ public static Boolean isNetworkAvailable(Context context) { boolean connected = false; final ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); final NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo != null && netInfo.isConnectedOrConnecting()) { connected = true; } else if (netInfo != null && netInfo.isConnected() && cm.getActiveNetworkInfo().isAvailable()) { connected = true; } else if (netInfo != null && netInfo.isConnected()) { try { URL url = new URL("http://www.google.com"); HttpURLConnection urlc = (HttpURLConnection) url.openConnection(); urlc.setConnectTimeout(3000); urlc.connect(); if (urlc.getResponseCode() == 200) { connected = true; } } catch (MalformedURLException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else if (cm != null) { final NetworkInfo[] netInfoAll = cm.getAllNetworkInfo(); for (NetworkInfo ni : netInfoAll) { System.out.println("get network type :::" + ni.getTypeName()); if ((ni.getTypeName().equalsIgnoreCase("WIFI") || ni.getTypeName().equalsIgnoreCase("MOBILE")) && ni.isConnected() && ni.isAvailable()) { connected = true; if (connected) { break; } } } } return connected; }
From source file:net.sf.taverna.t2.renderers.RendererUtils.java
public static long getSizeInBytes(Path path) throws IOException { if (isValue(path)) return Files.size(path); if (!isReference(path)) throw new IllegalArgumentException("Path is not a value or reference"); URL url = getReference(path).toURL(); switch (url.getProtocol().toLowerCase()) { case "http": case "https": HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("HEAD"); conn.connect(); String contentLength = conn.getHeaderField("Content-Length"); conn.disconnect();//from ww w . ja va2 s . co m if (contentLength != null && !contentLength.isEmpty()) return Long.parseLong(contentLength); return -1; case "file": return FileUtils.toFile(url).length(); default: return -1; } }
From source file:Main.java
public static String loadImageFromUrl(Context context, String imageURL, File file) { try {//ww w . j a v a 2s. c o m URL url = new URL(imageURL); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setConnectTimeout(5 * 1000); con.setDoInput(true); con.connect(); if (con.getResponseCode() == 200) { InputStream inputStream = con.getInputStream(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024 * 20]; int length = -1; while ((length = inputStream.read(buffer)) != -1) { byteArrayOutputStream.write(buffer, 0, length); } byteArrayOutputStream.close(); inputStream.close(); FileOutputStream outputStream = new FileOutputStream(file); outputStream.write(byteArrayOutputStream.toByteArray()); outputStream.close(); return file.getPath(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ""; }
From source file:Main.java
public static boolean isAvailable(String urlString) throws IOException { try {//from w w w .j av a 2 s .co m StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); URL url = new URL(urlString); HttpURLConnection urlc = (HttpURLConnection) url.openConnection(); urlc.setRequestProperty("Connection", "close"); urlc.setConnectTimeout(1000); urlc.connect(); if (urlc.getResponseCode() == 200) { return true; } else { return false; } } catch (Exception e) { e.printStackTrace(); } return false; }
From source file:Main.java
public static Bitmap decodeBitmapFromURL(String src, boolean large) { // If the artwork returned null, don't want to try to show artwork if (src.equals("null")) { return null; }/*from w w w.j a v a 2 s.com*/ if (large) { src = src.replace("large", "t500x500"); } InputStream inputStream = null; try { URL url = new URL(src); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.connect(); inputStream = connection.getInputStream(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if (inputStream == null) { return null; } // Decided not to scale because would have to recreate input stream /* final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(inputStream, null, options); options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); options.inJustDecodeBounds = false; */ Bitmap returnBitmap = BitmapFactory.decodeStream(inputStream); return returnBitmap; }