List of usage examples for java.net URLConnection setUseCaches
public void setUseCaches(boolean usecaches)
From source file:io.bitsquare.common.util.Utilities.java
public static String readTextFileFromServer(String url, String userAgent) throws IOException { URLConnection connection = URI.create(url).toURL().openConnection(); connection.setDoOutput(true);//w w w.j av a 2 s . c om connection.setUseCaches(false); connection.setConnectTimeout((int) TimeUnit.SECONDS.toMillis(10)); connection.addRequestProperty("User-Agent", userAgent); connection.connect(); try (InputStream inputStream = connection.getInputStream()) { return CharStreams.toString(new InputStreamReader(inputStream, Charsets.UTF_8)); } catch (IOException e) { e.printStackTrace(); throw e; } }
From source file:ru.codeinside.gses.webui.form.JsonForm.java
static String loadTemplate(ActivitiApp app, String ref) { try {//from w w w . j a v a2 s .c om URL serverUrl = app.getServerUrl(); URL url = new URL(serverUrl, ref); logger().info("fetch template " + url); URLConnection connection = url.openConnection(); connection.setDoOutput(false); connection.setDoInput(true); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); connection.setUseCaches(false); connection.connect(); return Streams.toString(connection.getInputStream()); } catch (MalformedURLException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:BihuHttpUtil.java
public static String doHttpPost(String xmlInfo, String URL) { System.out.println("??:" + xmlInfo); byte[] xmlData = xmlInfo.getBytes(); InputStream instr = null;//from w ww. j a va 2s .co m java.io.ByteArrayOutputStream out = null; try { URL url = new URL(URL); URLConnection urlCon = url.openConnection(); urlCon.setDoOutput(true); urlCon.setDoInput(true); urlCon.setUseCaches(false); urlCon.setRequestProperty("Content-Type", "text/xml"); urlCon.setRequestProperty("Content-length", String.valueOf(xmlData.length)); System.out.println(String.valueOf(xmlData.length)); DataOutputStream printout = new DataOutputStream(urlCon.getOutputStream()); printout.write(xmlData); printout.flush(); printout.close(); instr = urlCon.getInputStream(); byte[] bis = IOUtils.toByteArray(instr); String ResponseString = new String(bis, "UTF-8"); if ((ResponseString == null) || ("".equals(ResponseString.trim()))) { System.out.println(""); } System.out.println("?:" + ResponseString); return ResponseString; } catch (Exception e) { e.printStackTrace(); return "0"; } finally { try { out.close(); instr.close(); } catch (Exception ex) { return "0"; } } }
From source file:org.motechproject.mmnaija.web.util.HTTPCommunicator.java
public static String doPost(String serviceUrl, String queryString) { URLConnection connection = null; try {/*from w w w .j av a 2 s. c om*/ URL url = new URL(serviceUrl); URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef()); url = uri.toURL(); // Open the connection connection = url.openConnection(); connection.setDoInput(true); connection.setUseCaches(false); // Disable caching the document connection.setDoOutput(true); // Triggers POST. connection.setRequestProperty("Content-Type", "text/html"); OutputStreamWriter writer = null; log.info("About to write"); try { if (null != connection.getOutputStream()) { writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(queryString); // Write POST query } else { log.warn("connection Null"); } // string. } catch (ConnectException ex) { log.warn("Exception : " + ex); // ex.printStackTrace(); } finally { if (writer != null) { try { writer.close(); } catch (Exception lg) { log.warn("Exception lg: " + lg.toString()); //lg.printStackTrace(); } } } InputStream in = connection.getInputStream(); // StringWriter writer = new StringWriter(); IOUtils.copy(in, writer, "utf-8"); String theString = writer.toString(); return theString; } catch (Exception e) { //e.printStackTrace(); log.warn("Error URL " + e.toString()); return ""; } }
From source file:org.dhatim.util.ClassUtil.java
private static <T> void addClasses(URL url, Class<T> instanceOf, List<Class<T>> classes) { InputStream ins = null;//from w ww . j a va 2s .co m BufferedReader br = null; try { String className; int count = 0; // Get the input stream from the connection. Need to set the defaultUseCaches URLConnection connection = url.openConnection(); connection.setUseCaches(true); ins = connection.getInputStream(); br = new BufferedReader(new InputStreamReader(ins)); while ((className = br.readLine()) != null) { Class clazz; className = className.trim(); // Ignore blank lines and lines that start with a hash... if (className.equals("") || className.startsWith("#")) { continue; } try { clazz = forName(className, ClassUtil.class); } catch (ClassNotFoundException e) { logger.debug("Failed to load class '" + className + "'. Class not found.", e); continue; } if (instanceOf.isAssignableFrom(clazz)) { if (!contains(clazz.getName(), classes)) { classes.add(clazz); } logger.debug("Adding " + className + " to list of classes"); count++; } else { logger.debug("Not adding class '" + clazz.getName() + "' to list. Class does not implement/extend '" + instanceOf.getName() + "'."); } } logger.debug("Loaded '" + count + "' classes listed in '" + url + "'."); } catch (IOException e) { throw new RuntimeException("Failed to read from file : " + url, e); } finally { close(br); close(ins); } }
From source file:com.impetus.kundera.loader.PersistenceXMLLoader.java
/** * Reads the persistence xml content into an object graph and validates it * against the related xsd schema.//from w w w. ja va 2 s . co m * * @param pathToPersistenceXml * path to the persistence.xml file * @return parsed persistence xml as object graph * @throws InvalidConfigurationException * if the file could not be parsed or is not valid against the * schema */ private static Document getDocument(URL pathToPersistenceXml) throws InvalidConfigurationException { InputStream is = null; Document xmlRootNode = null; try { if (pathToPersistenceXml != null) { URLConnection conn = pathToPersistenceXml.openConnection(); conn.setUseCaches(false); // avoid JAR locking on Windows and // Tomcat. is = conn.getInputStream(); } if (is == null) { throw new IOException("Failed to obtain InputStream from url: " + pathToPersistenceXml); } xmlRootNode = parseDocument(is); validateDocumentAgainstSchema(xmlRootNode); } catch (IOException e) { throw new InvalidConfigurationException(e); } finally { if (is != null) { try { is.close(); } catch (IOException ex) { log.warn("Input stream could not be closed after parsing persistence.xml, caused by: {}", ex); } } } return xmlRootNode; }
From source file:net.pms.util.OpenSubtitle.java
public static String postPage(URLConnection connection, String query) throws IOException { connection.setDoOutput(true);//from ww w. j a v a2 s .co m connection.setDoInput(true); connection.setUseCaches(false); connection.setDefaultUseCaches(false); connection.setRequestProperty("Content-Type", "text/xml"); connection.setRequestProperty("Content-Length", "" + query.length()); ((HttpURLConnection) connection).setRequestMethod("POST"); //LOGGER.debug("opensub query "+query); // open up the output stream of the connection if (!StringUtils.isEmpty(query)) { try (DataOutputStream output = new DataOutputStream(connection.getOutputStream())) { output.writeBytes(query); output.flush(); } } StringBuilder page; try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { page = new StringBuilder(); String str; while ((str = in.readLine()) != null) { page.append(str.trim()); page.append("\n"); } } //LOGGER.debug("opensubs result page "+page.toString()); return page.toString(); }
From source file:tkwatch.Utilities.java
/** * Issues a TradeKing API request. Adapted from the <i>TradeKing API * Reference Guide</i>, 03.25.2011, p. 51. * //w ww. ja v a 2 s . c o m * @param resourceUrl * The URL to which API requests must be made. * @param body * The body of the API request. * @param appKey * The user's application key. * @param userKey * The user's key. * @param userSecret * The user's secret key. * @return Returns the result of the API request. */ public static final String tradeKingRequest(final String resourceUrl, final String body, final String appKey, final String userKey, final String userSecret) { String response = new String(); try { String timestamp = String.valueOf(Calendar.getInstance().getTimeInMillis()); String request_data = body + timestamp; String signature = generateSignature(request_data, userSecret); URL url = new URL(resourceUrl); URLConnection conn = url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestProperty("Content-Type", "application/xml"); conn.setRequestProperty("Accept", "application/xml"); conn.setRequestProperty("TKI_TIMESTAMP", timestamp); conn.setRequestProperty("TKI_SIGNATURE", signature); conn.setRequestProperty("TKI_USERKEY", userKey); conn.setRequestProperty("TKI_APPKEY", appKey); DataOutputStream out = new DataOutputStream(conn.getOutputStream()); out.writeBytes(body); out.flush(); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String temp; while ((temp = in.readLine()) != null) { response += temp + "\n"; } in.close(); return response; } catch (java.security.SignatureException e) { errorMessage(e.getMessage()); return ""; } catch (java.io.IOException e) { errorMessage(e.getMessage()); return ""; } }
From source file:org.spoutcraft.launcher.util.Utils.java
public static String executePost(String targetURL, String urlParameters, JProgressBar progress) throws PermissionDeniedException { URLConnection connection = null; try {// w w w.j ava2s. c om URL url = new URL(targetURL); connection = url.openConnection(); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length)); connection.setRequestProperty("Content-Language", "en-US"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); connection.setConnectTimeout(10000); connection.connect(); DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); StringBuilder response = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); return response.toString(); } catch (SocketException e) { if (e.getMessage().equalsIgnoreCase("Permission denied: connect")) { throw new PermissionDeniedException("Permission to login was denied"); } } catch (Exception e) { String message = "Login failed..."; progress.setString(message); } return null; }
From source file:org.codehaus.groovy.grails.io.support.GrailsResourceUtils.java
public static void useCachesIfNecessary(URLConnection con) { con.setUseCaches(con.getClass().getName().startsWith("JNLP")); }