List of usage examples for java.net URLConnection getInputStream
public InputStream getInputStream() throws IOException
From source file:com.easou.common.util.CommonUtils.java
/** * Contacts the remote URL and returns the response. * // w ww. ja va 2 s. c om * @param constructedUrl * the url to contact. * @param hostnameVerifier * Host name verifier to use for HTTPS connections. * @param encoding * the encoding to use. * @return the response. */ public static String getResponseFromServer(final URL constructedUrl, final HostnameVerifier hostnameVerifier, final String encoding) { URLConnection conn = null; try { conn = constructedUrl.openConnection(); if (conn instanceof HttpsURLConnection) { ((HttpsURLConnection) conn).setHostnameVerifier(hostnameVerifier); } final BufferedReader in; if (CommonUtils.isEmpty(encoding)) { in = new BufferedReader(new InputStreamReader(conn.getInputStream())); } else { in = new BufferedReader(new InputStreamReader(conn.getInputStream(), encoding)); } String line; final StringBuilder stringBuffer = new StringBuilder(255); while ((line = in.readLine()) != null) { stringBuffer.append(line); stringBuffer.append("\n"); } return stringBuffer.toString(); } catch (final Exception e) { LOG.error(e.getMessage(), e); throw new RuntimeException(e); } finally { if (conn != null && conn instanceof HttpURLConnection) { ((HttpURLConnection) conn).disconnect(); } } }
From source file:fr.gael.dhus.service.ProductService.java
private static boolean checkUrl(URL url) { Objects.requireNonNull(url, "`url` parameter must not be null"); // OData Synchronized product, DELME if (url.getPath().endsWith("$value")) { // Ignoring ... return true; }/*w w w .j ava 2s .co m*/ // Case of simple file try { File f = new File(url.toString()); if (f.exists()) return true; } catch (Exception e) { logger.debug("url \"" + url + "\" not formatted as a file"); } // Case of local URL try { URI local = new File(".").toURI(); URI uri = local.resolve(url.toURI()); File f = new File(uri); if (f.exists()) return true; } catch (Exception e) { logger.debug("url \"" + url + "\" not a local URL"); } // Case of remote URL try { URLConnection con = url.openConnection(); con.connect(); InputStream is = con.getInputStream(); is.close(); return true; } catch (Exception e) { logger.debug("url \"" + url + "\" not a remote URL"); } // Unrecovrable case return false; }
From source file:com.clavain.alerts.Methods.java
public static boolean sendSMSMessage(String message, String mobile_nr) { boolean retval = false; // http://smsflatrate.net/schnittstelle.php?key=ff&to=00491734631526&type=4&text=ALERT:%20Notification%20Test%20(HTTPS)%20-%20HTTP%20Critical-%20OK%20String%20not%20found try {/* w w w .j a v a 2s . com*/ if (p.getProperty("sms.provider").equals("smsflatrate")) { String key = p.getProperty("smsflatrate.key"); String gw = p.getProperty("smsflatrate.gw"); if (mobile_nr.startsWith("0049")) { gw = p.getProperty("smsflatrate.gwde"); } String msg = URLEncoder.encode(message); URL url = new URL("http://smsflatrate.net/schnittstelle.php?key=" + key + "&to=" + mobile_nr + "&type=" + gw + "&text=" + msg); URLConnection conn = url.openConnection(); // open the stream and put it into BufferedReader BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; String resp = ""; while ((inputLine = br.readLine()) != null) { resp = inputLine; } //conn.getContent(); if (resp.trim().equals("100")) { retval = true; } } else if (p.getProperty("sms.provider").equals("bulksms")) { // http://bulksms.de:5567/eapi/submission/send_sms/2/2.0?username=ff&password=yt89hjfff98&message=Hey%20Fucker&msisdn=491734631526 String msg = URLEncoder.encode(message); URL url = new URL("http://bulksms.de:5567/eapi/submission/send_sms/2/2.0?username=" + p.getProperty("bulksms.username") + "&password=" + p.getProperty("bulksms.password") + "&message=" + msg + "&msisdn=" + mobile_nr); URLConnection conn = url.openConnection(); // open the stream and put it into BufferedReader BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; String resp = ""; while ((inputLine = br.readLine()) != null) { resp = inputLine; } //conn.getContent(); if (resp.trim().startsWith("0")) { retval = true; } } else if (p.getProperty("sms.provider").equals("twilio")) { // reformat number? if (mobile_nr.startsWith("00")) { mobile_nr = "+" + mobile_nr.substring(2, mobile_nr.length()); } else if (mobile_nr.startsWith("0")) { mobile_nr = "+" + mobile_nr.substring(1, mobile_nr.length()); } TwilioRestClient client = new TwilioRestClient(p.getProperty("twilio.accountsid"), p.getProperty("twilio.authtoken")); //String msg = URLEncoder.encode(message); // Build the parameters List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("To", mobile_nr)); params.add(new BasicNameValuePair("From", p.getProperty("twilio.fromnr"))); params.add(new BasicNameValuePair("Body", message)); MessageFactory messageFactory = client.getAccount().getMessageFactory(); Message tmessage = messageFactory.create(params); logger.info("twilio: msg send to " + mobile_nr + " sid: " + tmessage.getSid() + " status: " + tmessage.getStatus() + " twilio emsg: " + tmessage.getErrorMessage()); } else if (p.getProperty("sms.provider").equals("script")) { List<String> commands = new ArrayList<String>(); // add global timeout script commands.add(p.getProperty("sms.script")); commands.add(mobile_nr); commands.add(message); ProcessBuilder pb = new ProcessBuilder(commands).redirectErrorStream(true); logger.info("sms.script - Running: " + commands); Process p = pb.start(); Integer rv = p.waitFor(); } } catch (Exception ex) { retval = false; logger.error("sendSMSMessage Error: " + ex.getLocalizedMessage()); } return retval; }
From source file:com.spinn3r.api.BaseClient.java
public static void closeQuietly(URLConnection conn) { try {//from www . j av a2s . com if (conn != null) { InputStream is = conn.getInputStream(); if (is != null) { is.close(); } } } catch (IOException ignore) { } }
From source file:imageLines.ImageHelpers.java
/**Read a jpeg image from a url into a BufferedImage*/ public static BufferedImage readAsBufferedImage(URL imageURL) { InputStream i = null;/* w ww .j a v a2 s .co m*/ try { URLConnection u = imageURL.openConnection(); u.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.151 Safari/535.19"); if (u instanceof HttpURLConnection) { HttpURLConnection h = (HttpURLConnection) u; if (h.getResponseCode() == 403) throw new Exception("403 forbidden"); } i = u.getInputStream(); BufferedImage bi = ImageIO.read(i); return bi; } catch (Exception e) { System.out.println(e + " for " + imageURL.toString() + "\n"); return null; } finally { try { i.close(); } catch (IOException ex) { } } }
From source file:com.alvermont.javascript.tools.shell.ShellMain.java
/** * Read file or url specified by <tt>path</tt>. * @return file or url content as <tt>byte[]</tt> or as <tt>String</tt> if * <tt>convertToString</tt> is true. *//*from w w w.j a v a 2 s. c om*/ private static Object readFileOrUrl(String path, boolean convertToString) { URL url = null; // Assume path is URL if it contains dot and there are at least // 2 characters in the protocol part. The later allows under Windows // to interpret paths with driver letter as file, not URL. if (path.indexOf(':') >= 2) { try { url = new URL(path); } catch (MalformedURLException ex) { log.debug("MalformedURLException in readFileOrUrl", ex); } } InputStream is = null; int capacityHint = 0; if (url == null) { final File file = new File(path); capacityHint = (int) file.length(); try { is = new FileInputStream(file); } catch (IOException ex) { Context.reportError(ToolErrorReporter.getMessage("msg.couldnt.open", path)); return null; } } else { try { final URLConnection uc = url.openConnection(); is = uc.getInputStream(); capacityHint = uc.getContentLength(); // Ignore insane values for Content-Length if (capacityHint > (1 << 20)) { capacityHint = -1; } } catch (IOException ex) { Context.reportError( ToolErrorReporter.getMessage("msg.couldnt.open.url", url.toString(), ex.toString())); return null; } } if (capacityHint <= 0) { capacityHint = 4096; } byte[] data; try { try { data = Kit.readStream(is, capacityHint); } finally { is.close(); } } catch (IOException ex) { Context.reportError(ex.toString()); return null; } Object result; if (!convertToString) { result = data; } else { // Convert to String using the default encoding // XXX: Use 'charset=' argument of Content-Type if URL? result = new String(data); } return result; }
From source file:com.viettel.dms.download.DownloadFile.java
/** * Download file with urlConnection/*from w w w .j av a 2 s. com*/ * @author : BangHN * since : 1.0 */ public static void downloadWithURLConnection(String url, File output, File tmpDir) { BufferedOutputStream os = null; BufferedInputStream is = null; File tmp = null; try { VTLog.i("Download ZIPFile", "Downloading url :" + url); tmp = File.createTempFile("download", ".tmp", tmpDir); URL urlDownload = new URL(url); URLConnection cn = urlDownload.openConnection(); cn.addRequestProperty("session", HTTPClient.sessionID); cn.setConnectTimeout(CONNECT_TIMEOUT); cn.setReadTimeout(READ_TIMEOUT); cn.connect(); is = new BufferedInputStream(cn.getInputStream()); os = new BufferedOutputStream(new FileOutputStream(tmp)); //cp nht dung lng tp tin request fileSize = cn.getContentLength(); //vn c tr?ng hp khng c ContentLength if (fileSize < 0) { //mc nh = 4 MB fileSize = 4 * 1024 * 1024; } copyStream(is, os); tmp.renameTo(output); tmp = null; } catch (IOException e) { ServerLogger.sendLog("Download ZIPFile", e.getMessage() + "\n" + e.toString() + "\n" + url, false, TabletActionLogDTO.LOG_EXCEPTION); VTLog.e("UnexceptionLog", VNMTraceUnexceptionLog.getReportFromThrowable(e)); throw new RuntimeException(e); } catch (Exception e) { VTLog.e("UnexceptionLog", VNMTraceUnexceptionLog.getReportFromThrowable(e)); ServerLogger.sendLog("Download ZIPFile", e.getMessage() + "\n" + e.toString() + "\n" + url, false, TabletActionLogDTO.LOG_EXCEPTION); throw new RuntimeException(e); } finally { if (tmp != null) { try { tmp.delete(); tmp = null; } catch (Exception ignore) { ; } } if (is != null) { try { is.close(); is = null; } catch (Exception ignore) { ; } } if (os != null) { try { os.close(); os = null; } catch (Exception ignore) { ; } } } }
From source file:biz.varkon.shelvesom.provider.comics.ComicsStore.java
public static String sendGetRequest(String id) { String result = null;// w ww .ja va 2 s . co m // Send a GET request to the servlet try { // Send data String urlStr = "http://" + mHost + CVInfo.buildGetPublisherQuery(id).build().toString(); URL url = new URL(urlStr); URLConnection conn = url.openConnection(); // Get the response BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer sb = new StringBuffer(); String line; while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); result = sb.toString(); } catch (Exception e) { e.printStackTrace(); } String[] restOfResult = result.split("name\": "); String resultName = restOfResult[1].substring(0, restOfResult[1].indexOf("}")); return resultName.replaceAll("\"", ""); }
From source file:com.google.dart.tools.update.core.internal.UpdateUtils.java
/** * Download a URL to a local file, notifying the given monitor along the way. *//*from w ww .j a v a 2s . c o m*/ public static void downloadFile(URL downloadUrl, File destFile, String taskName, IProgressMonitor monitor) throws IOException { URLConnection connection = downloadUrl.openConnection(); FileOutputStream out = new FileOutputStream(destFile); int length = connection.getContentLength(); monitor.beginTask(taskName, length); copyStream(connection.getInputStream(), out, monitor, length); monitor.done(); }
From source file:dictinsight.utils.io.HttpUtils.java
public static String getDataFromOtherServer(String url, String param) { PrintWriter out = null;// ww w . j av a 2 s.c o m BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); URLConnection conn = realUrl.openConnection(); conn.setConnectTimeout(1000 * 10); conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); conn.setDoOutput(true); conn.setDoInput(true); out = new PrintWriter(conn.getOutputStream()); out.print(param); out.flush(); in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("get date from " + url + param + " error!"); e.printStackTrace(); } // finally????? finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; }