List of usage examples for java.net URL openConnection
public URLConnection openConnection() throws java.io.IOException
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; }/* w w w .j a va 2 s. c om*/ 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; }
From source file:Main.java
/** * @param http//from w w w.ja v a 2 s . c o m * @return extracted title of page from html. * @throws IOException */ public static String getPageTitle(String linkUrl) throws IOException { URL url = new URL(linkUrl); URLConnection conn = null; try { conn = url.openConnection(); String type = conn.getContentType(); if (type != null && !type.toLowerCase().contains("text/html")) return null; // if not html, we can't get title. Return from here. else { // read response stream BufferedReader bufReader = new BufferedReader( new InputStreamReader(conn.getInputStream(), Charset.defaultCharset())); int n = 0; int readCount = 0; char[] buf = new char[1024]; StringBuilder content = new StringBuilder(); // read till end of file or 8 times the buffer (no need to read // all data, assuming we get content in first 8 reads) while (readCount < 8 && (n = bufReader.read(buf, 0, buf.length)) != -1) { content.append(buf, 0, n); readCount++; } bufReader.close(); // extract the title Matcher matcher = HTML_TITLE_PATTERN.matcher(content); if (matcher.find()) { // replace whitespaces and HTML brackets return matcher.group(1).replaceAll("[\\s\\<>]+", " ").trim(); } else return null; } } finally { //any cleanup? } }
From source file:Main.java
static public String downloadFile(String downloadUrl, String fileName, String dir) throws IOException { URL url = new URL(downloadUrl); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setDoOutput(true);/* w w w .java 2 s .co m*/ urlConnection.connect(); int code = urlConnection.getResponseCode(); if (code > 300 || code == -1) { throw new IOException("Cannot read url: " + downloadUrl); } String filePath = prepareFilePath(fileName, dir); String tmpFilePath = prepareTmpFilePath(fileName, dir); FileOutputStream fileOutput = new FileOutputStream(tmpFilePath); BufferedInputStream inputStream = new BufferedInputStream(urlConnection.getInputStream()); byte[] buffer = new byte[1024]; int bufferLength; while ((bufferLength = inputStream.read(buffer)) > 0) { fileOutput.write(buffer, 0, bufferLength); } fileOutput.close(); // move tmp to destination copyFile(new File(tmpFilePath), new File(filePath)); return filePath; }
From source file:Main.java
/** * This method checks if the Network available on the device or not. * /*from w w w . ja va 2s. c om*/ * @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:com.francelabs.datafari.utils.SendHttpRequest.java
public static void sendGET(String url, String userAgent) throws IOException { URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("User-Agent", userAgent); int responseCode = con.getResponseCode(); logger.debug("GET Response Code :: " + responseCode); if (responseCode == HttpURLConnection.HTTP_OK) { // success BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine;// w w w . ja va 2 s.c o m StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // print result logger.debug(response.toString()); } else { logger.debug("GET request not worked"); } }
From source file:org.cytoscape.app.internal.net.server.ScreenOriginsBeforeResponseTest.java
private static HttpURLConnection connectToURL(String urlString, String method, String origin) throws Exception { final URL url = new URL(urlString); final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(method); connection.setDoOutput(true);// w w w. j a v a 2 s . c o m if (origin != null) connection.setRequestProperty("Origin", origin); connection.setConnectTimeout(1000); connection.connect(); return connection; }
From source file:Authentication.DinserverAuth.java
public static boolean Login(String nick, String pass, Socket socket) throws IOException { boolean logged = false; JSONObject authRequest = new JSONObject(); authRequest.put("username", nick); authRequest.put("auth_id", pass); String query = "http://127.0.0.1:5000/token"; URL url = new URL(query); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000);//from w ww . j ava2 s . c o m conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); OutputStream os = conn.getOutputStream(); os.write(authRequest.toString().getBytes(Charset.forName("UTF-8"))); os.close(); String output = new String(); StringBuilder sb = new StringBuilder(); int HttpResult = conn.getResponseCode(); if (HttpResult == HttpURLConnection.HTTP_OK) { output = IOUtils.toString(new InputStreamReader(conn.getInputStream(), Charset.forName("UTF-8"))); } else { System.out.println(conn.getResponseMessage()); } JSONObject jsonObject = new JSONObject(output); logged = jsonObject.getBoolean("ok"); conn.disconnect(); if (logged) { if (DinserverMaster.addUser(nick, socket)) { System.out.println("User " + nick + " logged in"); } else { logged = false; } } return logged; }
From source file:Main.java
public static String getHtml(String getUrl, int outtime, String charsetName) { String html = ""; URL url; try {/*from w w w. j a v a 2s . c o m*/ url = new URL(getUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; InfoPath.1; CIBA)"); // connection.setRequestProperty("Connection", "Keep-Alive"); // connection.setRequestProperty("Cache-Control", "no-cache"); connection.setConnectTimeout(outtime); connection.connect(); InputStream inStrm = connection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(inStrm, charsetName)); String temp = ""; while ((temp = br.readLine()) != null) { html = html + (temp + '\n'); } try { br.close(); } catch (Exception e) { // TODO: handle exception } try { connection.disconnect(); } catch (Exception e) { // TODO: handle exception } } catch (Exception e) { e.printStackTrace(); } return html; }
From source file:Main.java
public static byte[] getHtmlByteArray(final String url) { URL htmlUrl; InputStream inStream = null;//from w w w . j av a2 s . c o m try { htmlUrl = new URL(url); URLConnection connection = htmlUrl.openConnection(); HttpURLConnection httpConnection = (HttpURLConnection) connection; int responseCode = httpConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { inStream = httpConnection.getInputStream(); } } catch (IOException e) { e.printStackTrace(); } byte[] data = inputStreamToByte(inStream); return data; }
From source file:me.prokopyl.commandtools.migration.UUIDFetcher.java
private static HttpURLConnection createConnection() throws IOException { URL url = new URL(PROFILE_URL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setUseCaches(false);// w w w . j a v a 2 s . co m connection.setDoInput(true); connection.setDoOutput(true); return connection; }