List of usage examples for java.net HttpURLConnection disconnect
public abstract void disconnect();
From source file:lu.list.itis.dkd.aig.util.FusekiHttpHelper.java
/** * Check if specified dataset already exists on server * /*from w w w.j a va2 s . c om*/ * @param dataSetName * @return boolean true if the dataset already exits, false if not * @throws IOException * @throws HttpException */ public static boolean chechIfExist(String dataSetName) throws IOException, HttpException { boolean exists = false; URL url = new URL(HOST + "/$/datasets/" + dataSetName); final HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection(); httpConnection.setUseCaches(false); httpConnection.setRequestMethod("GET"); // handle HTTP/HTTPS strange behaviour httpConnection.connect(); httpConnection.disconnect(); // handle response switch (httpConnection.getResponseCode()) { case HttpURLConnection.HTTP_OK: exists = true; break; case HttpURLConnection.HTTP_NOT_FOUND: break; default: throw new HttpException( httpConnection.getResponseCode() + " message: " + httpConnection.getResponseMessage()); } return exists; }
From source file:Main.java
/** * Send the Http's request with the address of url * @param String url//ww w. jav a 2 s.c om * @return String */ public static String getHttpRequest(String url) { //should use the StringBuilder or StringBuffer, String is not used. StringBuffer jsonContent = new StringBuffer(); try { URL getUrl = new URL(url); HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection(); connection.connect(); //Getting the inputting stream, and then read the stream. BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String lines = ""; while ((lines = reader.readLine()) != null) { jsonContent.append(lines); } reader.close(); connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } //ScanningActivity.log("getHttpRequest(): " + content); //BooksPutIn.log("getHttpRequest(): " + content); return jsonContent.toString(); }
From source file:Main.java
/** * Given a string url, connects and returns response code * * @param urlString string to fetch * @param readTimeOutMs read time out * @param connectionTimeOutMs connection time out * @param urlRedirect should use urlRedirect * @param useCaches should use cache * @return httpResponseCode http response code * @throws IOException/*from www . j av a2 s . c o m*/ */ public static int checkUrlWithOptions(String urlString, int readTimeOutMs, int connectionTimeOutMs, boolean urlRedirect, boolean useCaches) throws IOException { URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setReadTimeout(readTimeOutMs /* milliseconds */); connection.setConnectTimeout(connectionTimeOutMs /* milliseconds */); connection.setRequestMethod("GET"); connection.setInstanceFollowRedirects(urlRedirect); connection.setUseCaches(useCaches); // Starts the query connection.connect(); int responseCode = connection.getResponseCode(); connection.disconnect(); return responseCode; }
From source file:Main.java
/** * Given a string url, connects and returns response code * * @param urlString string to fetch * @param network network/*from w w w.j a va 2s . c o m*/ * @param readTimeOutMs read time out * @param connectionTimeOutMs connection time out * @param urlRedirect should use urlRedirect * @param useCaches should use cache * @return httpResponseCode http response code * @throws IOException */ @TargetApi(LOLLIPOP) public static int checkUrlWithOptionsOverNetwork(String urlString, Network network, int readTimeOutMs, int connectionTimeOutMs, boolean urlRedirect, boolean useCaches) throws IOException { if (network == null) { return -1; } URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) network.openConnection(url); connection.setReadTimeout(readTimeOutMs /* milliseconds */); connection.setConnectTimeout(connectionTimeOutMs /* milliseconds */); connection.setRequestMethod("GET"); connection.setInstanceFollowRedirects(urlRedirect); connection.setUseCaches(useCaches); // Starts the query connection.connect(); int responseCode = connection.getResponseCode(); connection.disconnect(); return responseCode; }
From source file:com.jts.rest.profileservice.utils.RestServiceHelper.java
/** * Makes a get request to the given url and returns the json object * @param sessionId//from w ww . ja va 2s . c o m * @param url * @return * @throws MalformedURLException * @throws IOException */ public static JSONArray makeGetRequest(String sessionId, String url) throws MalformedURLException, IOException { URL endpoint = new URL(url); HttpURLConnection urlc = (HttpURLConnection) endpoint.openConnection(); urlc.setRequestProperty("Authorization", "OAuth " + sessionId); urlc.setRequestMethod("GET"); urlc.setDoOutput(true); String output = OauthHelperUtils.readInputStream(urlc.getInputStream()); urlc.disconnect(); Object json = JSONValue.parse(output); JSONArray jsonArr = (JSONArray) json; return jsonArr; }
From source file:de.egore911.versioning.deployer.Main.java
private static void perform(String arg, CommandLine line) throws IOException { URL url;/* w ww .j a va 2 s.com*/ try { url = new URL(arg); } catch (MalformedURLException e) { LOG.error("Invalid URI: {}", e.getMessage(), e); System.exit(1); return; } HttpURLConnection connection; try { connection = (HttpURLConnection) url.openConnection(); int response = connection.getResponseCode(); if (response != HttpURLConnection.HTTP_OK) { LOG.error("Could not download {}", url); connection.disconnect(); System.exit(1); return; } } catch (ConnectException e) { LOG.error("Error during download from URI {}: {}", url, e.getMessage()); System.exit(1); return; } XmlHolder xmlHolder = XmlHolder.getInstance(); DocumentBuilder documentBuilder = xmlHolder.documentBuilder; XPath xPath = xmlHolder.xPath; try { XPathExpression serverNameXpath = xPath.compile("/server/name/text()"); XPathExpression serverTargetdirXpath = xPath.compile("/server/targetdir/text()"); XPathExpression serverDeploymentsDeploymentXpath = xPath.compile("/server/deployments/deployment"); Document doc = documentBuilder.parse(connection.getInputStream()); connection.disconnect(); String serverName = (String) serverNameXpath.evaluate(doc, XPathConstants.STRING); LOG.info("Deploying {}", serverName); boolean shouldPerformCopy = !line.hasOption('r'); PerformCopy performCopy = new PerformCopy(xPath); boolean shouldPerformExtraction = !line.hasOption('r'); PerformExtraction performExtraction = new PerformExtraction(xPath); boolean shouldPerformCheckout = !line.hasOption('r'); PerformCheckout performCheckout = new PerformCheckout(xPath); boolean shouldPerformReplacement = true; PerformReplacement performReplacement = new PerformReplacement(xPath); String targetdir = (String) serverTargetdirXpath.evaluate(doc, XPathConstants.STRING); FileUtils.forceMkdir(new File(targetdir)); NodeList serverDeploymentsDeploymentNodes = (NodeList) serverDeploymentsDeploymentXpath.evaluate(doc, XPathConstants.NODESET); int max = serverDeploymentsDeploymentNodes.getLength(); for (int i = 0; i < serverDeploymentsDeploymentNodes.getLength(); i++) { Node serverDeploymentsDeploymentNode = serverDeploymentsDeploymentNodes.item(i); // Copy if (shouldPerformCopy) { performCopy.perform(serverDeploymentsDeploymentNode); } // Extraction if (shouldPerformExtraction) { performExtraction.perform(serverDeploymentsDeploymentNode); } // Checkout if (shouldPerformCheckout) { performCheckout.perform(serverDeploymentsDeploymentNode); } // Replacement if (shouldPerformReplacement) { performReplacement.perform(serverDeploymentsDeploymentNode); } logPercent(i + 1, max); } // validate that "${versioning:" is not present Collection<File> files = FileUtils.listFiles(new File(targetdir), TrueFileFilter.TRUE, TrueFileFilter.INSTANCE); for (File file : files) { String content; try { content = FileUtils.readFileToString(file); } catch (IOException e) { continue; } if (content.contains("${versioning:")) { LOG.error("{} contains placeholders even after applying the replacements", file.getAbsolutePath()); } } LOG.info("Done deploying {}", serverName); } catch (SAXException | IOException | XPathExpressionException e) { LOG.error("Error performing deployment: {}", e.getMessage(), e); } }
From source file:com.rumblefish.friendlymusic.api.WebRequest.java
public static Bitmap getBitmapAtURL(URL url) { InputStream inStream = null;/*from w w w .ja va2s . co m*/ HttpURLConnection _conn = null; Bitmap bitmap = null; try { _conn = (HttpURLConnection) url.openConnection(); _conn.setDoInput(true); _conn.connect(); inStream = _conn.getInputStream(); bitmap = BitmapFactory.decodeStream(inStream); inStream.close(); _conn.disconnect(); inStream = null; _conn = null; } catch (Exception ex) { // nothing } if (inStream != null) { try { inStream.close(); } catch (Exception ex) { } } if (_conn != null) { _conn.disconnect(); } return bitmap; }
From source file:com.adguard.compiler.UrlUtils.java
public static String downloadString(URL url, String encoding, String userAgent) throws IOException { HttpURLConnection connection = null; InputStream inputStream = null; try {//from ww w. j a va 2s .c o m connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); inputStream = connection.getInputStream(); return IOUtils.toString(inputStream, encoding); } finally { IOUtils.closeQuietly(inputStream); if (connection != null) { connection.disconnect(); } } }
From source file:Main.java
public static long downloadFileFromUrl(String urlPath, File file) { long size = 0; try {/* w ww . java2 s .c om*/ URL url = new URL(urlPath); HttpURLConnection httpurlconnection = (HttpURLConnection) url.openConnection(); BufferedInputStream bufferedinputstream = new BufferedInputStream(httpurlconnection.getInputStream()); BufferedOutputStream bufferedoutputstream = new BufferedOutputStream(new FileOutputStream(file)); int i; while ((i = bufferedinputstream.read()) != -1) { bufferedoutputstream.write(i); } bufferedinputstream.close(); bufferedoutputstream.close(); httpurlconnection.disconnect(); size = file.length(); } catch (Exception e) { e.printStackTrace(); } return size; }
From source file:com.ibuildapp.romanblack.CataloguePlugin.imageloader.Utils.java
public static String downloadFile(Context context, String url, String md5) { final int BYTE_ARRAY_SIZE = 8024; final int CONNECTION_TIMEOUT = 30000; final int READ_TIMEOUT = 30000; try {// ww w .ja v a 2s.c o m for (int i = 0; i < 3; i++) { URL fileUrl = new URL(URLDecoder.decode(url)); HttpURLConnection connection = (HttpURLConnection) fileUrl.openConnection(); connection.setConnectTimeout(CONNECTION_TIMEOUT); connection.setReadTimeout(READ_TIMEOUT); connection.connect(); int status = connection.getResponseCode(); if (status >= HttpStatus.SC_BAD_REQUEST) { connection.disconnect(); continue; } BufferedInputStream bufferedInputStream = new BufferedInputStream(connection.getInputStream()); File file = new File(StaticData.getCachePath(context) + md5); if (!file.exists()) { new File(StaticData.getCachePath(context)).mkdirs(); file.createNewFile(); } FileOutputStream fileOutputStream = new FileOutputStream(file, false); int byteCount; byte[] buffer = new byte[BYTE_ARRAY_SIZE]; while ((byteCount = bufferedInputStream.read(buffer, 0, BYTE_ARRAY_SIZE)) != -1) fileOutputStream.write(buffer, 0, byteCount); bufferedInputStream.close(); fileOutputStream.flush(); fileOutputStream.close(); return file.getAbsolutePath(); } } catch (Exception e) { e.printStackTrace(); return null; } return null; }