List of usage examples for java.net HttpURLConnection connect
public abstract void connect() throws IOException;
From source file:com.entertailion.android.slideshow.utils.Utils.java
/** * Create a bitmap from a image URL.//from www . ja va 2s . com * * @param src * @return */ public static final Bitmap getBitmapFromURL(String src) { try { URL url = new URL(src); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.connect(); InputStream input = connection.getInputStream(); Bitmap myBitmap = BitmapFactory.decodeStream(input); int size = Math.max(myBitmap.getWidth(), myBitmap.getHeight()); Bitmap b = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888); Canvas c = new Canvas(b); Paint paint = new Paint(); paint.setAntiAlias(true); c.drawBitmap(myBitmap, (size - myBitmap.getWidth()) / 2, (size - myBitmap.getHeight()) / 2, paint); return b; } catch (Exception e) { Log.e(LOG_TAG, "Faild to get the image from URL:" + src, e); return null; } }
From source file:com.magnet.plugin.common.helpers.URLHelper.java
public static InputStream loadUrl(final String url) throws Exception { final InputStream[] inputStreams = new InputStream[] { null }; final Exception[] exception = new Exception[] { null }; Future<?> downloadThreadFuture = ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { public void run() { try { HttpURLConnection connection; if (ApplicationManager.getApplication() != null) { connection = HttpConfigurable.getInstance().openHttpConnection(url); } else { connection = (HttpURLConnection) new URL(url).openConnection(); connection.setReadTimeout(CONNECTION_TIMEOUT); connection.setConnectTimeout(CONNECTION_TIMEOUT); }/*from www .j a v a 2 s . co m*/ connection.connect(); inputStreams[0] = connection.getInputStream(); } catch (IOException e) { exception[0] = e; } } }); try { downloadThreadFuture.get(5, TimeUnit.SECONDS); } catch (TimeoutException ignored) { } if (!downloadThreadFuture.isDone()) { downloadThreadFuture.cancel(true); throw new Exception(IdeBundle.message("updates.timeout.error")); } if (exception[0] != null) throw exception[0]; return inputStreams[0]; }
From source file:com.dynamobi.db.conn.couchdb.CouchUdx.java
/** * Helper function gets the rows from the foreign CouchDB server and returns * them as a JSONArray./*w ww .ja v a2 s. com*/ */ private static InputStreamReader getViewStream(String user, String pw, String url, String view, String limit, boolean reduce, String groupLevel, boolean hasReducer) throws SQLException { String full_url = ""; try { // TODO: stringbuffer this for efficiency full_url = makeUrl(url, view); String sep = (view.indexOf("?") == -1) ? "?" : "&"; if (limit != null && limit.length() > 0) { full_url += sep + "limit=" + limit; sep = "&"; } // These options only apply if a reducer function is present. if (hasReducer) { if (!reduce) { full_url += sep + "reduce=false"; if (sep.equals("?")) sep = "&"; } if (groupLevel.toUpperCase().equals("EXACT")) full_url += sep + "group=true"; else if (groupLevel.toUpperCase().equals("NONE")) full_url += sep + "group=false"; else full_url += sep + "group_level=" + groupLevel; } logger.log(Level.FINE, "Attempting CouchDB request with URL: " + full_url); URL u = new URL(full_url); HttpURLConnection uc = (HttpURLConnection) u.openConnection(); if (user != null && user.length() > 0) { uc.setRequestProperty("Authorization", "Basic " + buildAuthHeader(user, pw)); } uc.connect(); return new InputStreamReader(uc.getInputStream()); } catch (MalformedURLException e) { throw new SQLException("Bad URL: " + full_url); } catch (IOException e) { if (hasReducer) { // try again but without the reduce args.. try { return getViewStream(user, pw, url, view, limit, reduce, groupLevel, false); } catch (SQLException e2) { // No good. } } throw new SQLException("Could not read data from URL: " + full_url); } }
From source file:net.cbtltd.server.WebService.java
/** * Gets the connection to the JSON server. * * @param url the connection URL./*from www .j av a2 s . com*/ * @param rq the request object. * @return the JSON string returned by the message. * @throws Throwable the exception thrown by the method. */ private static final String getConnection(URL url, String rq) throws Throwable { String jsonString = ""; HttpURLConnection connection = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); //connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/json"); if (rq != null) { connection.setRequestProperty("Accept", "application/json"); connection.connect(); byte[] outputBytes = rq.getBytes("UTF-8"); OutputStream os = connection.getOutputStream(); os.write(outputBytes); } if (connection.getResponseCode() != 200) { throw new RuntimeException("HTTP:" + connection.getResponseCode() + "URL " + url); } BufferedReader br = new BufferedReader(new InputStreamReader((connection.getInputStream()))); String line; while ((line = br.readLine()) != null) { jsonString += line; } } catch (Throwable x) { throw new RuntimeException(x.getMessage()); } finally { if (connection != null) { connection.disconnect(); } } return jsonString; }
From source file:com.crawler.app.run.CrawlSiteController.java
public static Boolean checkWebSite(URL url) { HttpURLConnection connection; int code = 0; try {//from w w w. ja v a 2 s . c o m connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); code = connection.getResponseCode(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (code == 200) { return true; } else { return false; } }
From source file:eu.liveandgov.ar.utilities.Download_Data.java
/** DownAndCopy * //from w w w. j a v a 2 s. com * Download file from URL and Copy to Android file system folder * * @param fileUrl * @param StringAndroidPath */ public static boolean DownAndCopy(String fileUrlSTR, String StringAndroidPath, boolean preservefilename, String Caller) { if (compareRemoteWithLocal(fileUrlSTR, StringAndroidPath)) { //Log.e("fileUrlSTR", "SKIP WITH HASH"); return true; } else { Log.e("TRY TO DOWNLOAD BY " + Caller, fileUrlSTR); } SimpleDateFormat sdf = new SimpleDateFormat("mm"); // Check if downloaded at least just 2 minutes ago for (String[] mem : MemDown) if (fileUrlSTR.equals(mem[0])) { int diff = Integer.parseInt(sdf.format(new Date())) - Integer.parseInt(mem[1]); Log.e("diff", " " + diff); if (diff < 2) { Log.d("Download_Data", "I am not downloading " + fileUrlSTR + " because it was downloaded " + diff + " minutes ago"); return true; } } if (!OS_Utils.exists(fileUrlSTR)) { Log.e("Download_Data", "URL: " + fileUrlSTR + " called from " + Caller + " not exists to copy it to " + StringAndroidPath); return false; } int DEBUG_FLAG = 0; HttpURLConnection conn; URL fileUrl = null; try { fileUrl = new URL(fileUrlSTR); } catch (MalformedURLException e1) { return false; } try { conn = (HttpURLConnection) fileUrl.openConnection(); DEBUG_FLAG = 1; conn.setDoInput(true); conn.connect(); InputStream is = conn.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); ByteArrayBuffer baf = new ByteArrayBuffer(100); DEBUG_FLAG = 2; int current = 0; byte[] buffer = new byte[10]; while ((current = bis.read(buffer)) != -1) baf.append(buffer, 0, current); DEBUG_FLAG = 3; /* Convert the Bytes read to a String. */ File fileAndroid; try { if (preservefilename) { int iSlash = fileUrlSTR.lastIndexOf("/"); fileAndroid = new File(StringAndroidPath + "/" + fileUrlSTR.substring(iSlash + 1)); } else fileAndroid = new File(StringAndroidPath); } catch (Exception e) { Log.e("Download_Data.DownAndCopy", "I can not create " + StringAndroidPath); bis.close(); conn.disconnect(); return false; } DEBUG_FLAG = 4; FileOutputStream fos = new FileOutputStream(fileAndroid); fos.write(baf.toByteArray()); DEBUG_FLAG = 5; bis.close(); fos.close(); conn.disconnect(); MemDown.add(new String[] { fileUrlSTR, sdf.format(new Date()) }); return true; //returns including the filename } catch (IOException e) { Log.e("Download_Data", "Download_Data: Error when trying to download: " + fileUrl.toString() + " to " + StringAndroidPath + " DEBUG_FLAG=" + DEBUG_FLAG); return false; } }
From source file:org.immopoly.android.helper.WebHelper.java
public static JSONObject getHttpData(URL url, boolean signed, Context context) throws JSONException { JSONObject obj = null;/*from w w w.j ava2 s.co m*/ if (Settings.isOnline(context)) { HttpURLConnection request; try { request = (HttpURLConnection) url.openConnection(); request.addRequestProperty("User-Agent", "immopoly android client " + ImmopolyActivity.getStaticVersionInfo()); request.addRequestProperty("Accept-Encoding", "gzip"); if (signed) OAuthData.getInstance(context).consumer.sign(request); request.setConnectTimeout(SOCKET_TIMEOUT); request.connect(); String encoding = request.getContentEncoding(); InputStream in; if (encoding != null && encoding.equalsIgnoreCase("gzip")) { in = new GZIPInputStream(request.getInputStream()); } else { in = new BufferedInputStream(request.getInputStream()); } String s = readInputStream(in); JSONTokener tokener = new JSONTokener(s); obj = new JSONObject(tokener); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (OAuthMessageSignerException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (OAuthExpectationFailedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (OAuthCommunicationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return obj; }
From source file:com.talk.demo.util.NetworkUtilities.java
public static void downloadPhoto(final String photoName) { // If there is no photo, we're done if (TextUtils.isEmpty(photoName)) { return;/*w w w. j a v a 2s . c o m*/ } try { Log.i(TAG, "Downloading photo: " + DOWNLOAD_PHOTO_URI); // Request the photo from the server, and create a bitmap // object from the stream we get back. URL url = new URL(DOWNLOAD_PHOTO_URI + photoName + "/"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); try { final BitmapFactory.Options options = new BitmapFactory.Options(); final Bitmap photo = BitmapFactory.decodeStream(connection.getInputStream(), null, options); Log.d(TAG, "file name : " + photoName); TalkUtil.createDirAndSaveFile(photo, photoName); // On pre-Honeycomb systems, it's important to call recycle on bitmaps photo.recycle(); } finally { connection.disconnect(); } } catch (MalformedURLException muex) { // A bad URL - nothing we can really do about it here... Log.e(TAG, "Malformed avatar URL: " + DOWNLOAD_PHOTO_URI); } 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: " + DOWNLOAD_PHOTO_URI); } }
From source file:com.illusionaryone.FrankerZAPIv1.java
@SuppressWarnings("UseSpecificCatch") private static JSONObject readJsonFromUrl(String urlAddress) { JSONObject jsonResult = new JSONObject("{}"); InputStream inputStream = null; URL urlRaw;/*from w ww. jav a 2 s .c o m*/ HttpURLConnection urlConn; String jsonText = ""; try { urlRaw = new URL(urlAddress); urlConn = (HttpURLConnection) urlRaw.openConnection(); urlConn.setDoInput(true); urlConn.setRequestMethod("GET"); urlConn.addRequestProperty("Content-Type", "application/json"); urlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 PhantomBotJ/2015"); urlConn.connect(); if (urlConn.getResponseCode() == 200) { inputStream = urlConn.getInputStream(); } else { inputStream = urlConn.getErrorStream(); } BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8"))); jsonText = readAll(rd); jsonResult = new JSONObject(jsonText); fillJSONObject(jsonResult, true, "GET", urlAddress, urlConn.getResponseCode(), "", "", jsonText); } catch (JSONException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "JSONException", ex.getMessage(), jsonText); com.gmt2001.Console.err.printStackTrace(ex); } catch (NullPointerException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "NullPointerException", ex.getMessage(), ""); com.gmt2001.Console.err.printStackTrace(ex); } catch (MalformedURLException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "MalformedURLException", ex.getMessage(), ""); com.gmt2001.Console.err.printStackTrace(ex); } catch (SocketTimeoutException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "SocketTimeoutException", ex.getMessage(), ""); com.gmt2001.Console.err.printStackTrace(ex); } catch (IOException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), ""); com.gmt2001.Console.err.printStackTrace(ex); } catch (Exception ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "Exception", ex.getMessage(), ""); com.gmt2001.Console.err.printStackTrace(ex); } finally { if (inputStream != null) try { inputStream.close(); } catch (IOException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), ""); com.gmt2001.Console.err.printStackTrace(ex); } } return (jsonResult); }
From source file:circleplus.app.http.AbstractHttpApi.java
private static HttpURLConnection getHttpURLConnection(URL url, int requestMethod, boolean acceptJson) throws IOException { if (D)//from www. j a va 2 s . c o m Log.d(TAG, "execute method: " + requestMethod + " url: " + url.toString() + " accept JSON ?= " + acceptJson); String method; boolean isPost; switch (requestMethod) { case REQUEST_METHOD_GET: method = "GET"; isPost = false; break; case REQUEST_METHOD_POST: method = "POST"; isPost = true; break; default: method = "GET"; isPost = false; break; } HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(TIMEOUT); conn.setConnectTimeout(TIMEOUT); conn.setRequestProperty("Content-Type", JSON_UTF8_CONTENT_TYPE); if (isPost && acceptJson) { conn.setRequestProperty("Accept", JSON_CONTENT_TYPE); } conn.setRequestMethod(method); /* setDoOutput(true) equals setRequestMethod("POST") */ conn.setDoOutput(isPost); conn.setChunkedStreamingMode(0); // Starts the query conn.connect(); return conn; }